title: How to extend Swift 5 JSONEncoder to handle precision
body: <p>I have a problem where I need to encode a floating point value into JSON that maintains precision. For example, if the precision is to the hundredths, the value in the JSON string would be 2.00 and not 2 or 2.0. The problem would have been simple if the value type were encoded as a String and not a number. But that is out of my control. The FHIR spec requires that the encoding is <code>&quot;value&quot;: 2.00</code> and not <code>&quot;value&quot;: &quot;2.00&quot;</code></p>
  <p>In IEEE 11073 Medical Device communication protocols there is a special data type that assures precision. We can represent it by this struct</p>
  <pre><code>struct MderFloat
  {
      var exponent: Int
      var mantissa: Int
  }
  </code></pre>
  <p>The meaning of these terms is a little different than one might expect. The exponent gives the precision. So 2.00 would be given by a mantissa of 200 and an exponent of -2; basically the exponent tells you where the decimal point goes in the mantissa.</p>
  <p>So if I have a struct</p>
  <pre><code>struct TestIt
  {
      var title: String
      var value: MderFloat
  }
  </code></pre>
  <p>I would like the JSON encoding to look as follows:</p>
  <pre><code>{
      &quot;title&quot;: &quot;Some title&quot;
      &quot;value&quot;: 2.00
  }
  </code></pre>
  <p>Is there a way to do this perhaps using extensions? Can 'Decimal' be made to assure precision?</p>