title: Currency/monetary values -- How to store in a DB & transfer using JSON?
body: <p>What are the best practices for storing currency/monetary values in the DB, processing them in a server-side app, and finally sending them down to the browser via a JSON API?</p>
  
  <p>I've figured two approaches, but I'm not sure how to weigh out the pros &amp; cons:</p>
  
  <h2>Store values as integers in the smallest monetary unit</h2>
  
  <ul>
  <li>Basically this means that the database will store the monetary value in cents / paise / shillings / etc.</li>
  <li>The server side app will map this value to a regular integer variable.</li>
  <li>The JSON API will represent the value as a regular JSON number.</li>
  <li>The downside of this approach is that you have to constantly divide by 100 before displaying a monetary value to the user and always multiply by 100 before storing any user input.</li>
  <li>Possible gotchas: How do you define the smallest monetary unit? Is it on the basis of two decimal points or four? Is there any currency which does not have a 100:1 ratio, i.e. 100 cents = 1 dollar.</li>
  </ul>
  
  <h2>Store values as decimal/numeric with fixed precision &amp; scale</h2>
  
  <ul>
  <li>The DB stores the monetary value as a decimal/numeric type with a fixed precision &amp; scale, eg. NUMERIC(10,2)</li>
  <li>The server-side app maps these to special objects which can preserve the precision &amp; scale across computations, eg. <code>BigDecimal</code> in Ruby.</li>
  <li>The JSON API exchanges these values as <em>strings</em> and not numbers. Because numbers would automatically get parsed as floats by the JSON parser, thus causing loss in precision.</li>
  <li>The downside of this approach is that all computations on the server-side need to happen within a boxed data-type (possibly slower) AND that the JSON parsers needs to be aware of the the fact that certain strings are not actually strings, but numeric values.</li>
  <li>The upside of this is that you don't need to constantly multiply and divide by 100.</li>
  </ul>
  
  <p>Is there a generally accepted best practice for this?</p>