title: Native BigInt and Intl.NumberFormat for accurate currency calculations and display?
body: <p>As you probably know, <code>0.1 + 0.2 == 0.30000000000000004</code> in JavaScript. Limited precision when dealing with money can be a problem. To overcome this, one could use <a href="https://v8project.blogspot.com/2018/05/bigint.html" rel="nofollow noreferrer">BigInt</a>, which obviously requires integer values.</p>
  
  <p>Instead of dollars as base unit and cents as decimal fraction (e.g. <code>0.10</code> for ¢10) it is easy to use cents as base unit (<code>10</code> for ¢10) to make it integer-only.</p>
  
  <p>However, when presented to a user, you probably want to show the value in dollars, not cents. But you can't divide <code>BigInt</code> by <code>Number</code>:</p>
  
  <pre><code>&gt; BigInt(10) / 100
  Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
  </code></pre>
  
  <p>On the other hand, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat" rel="nofollow noreferrer">Intl.NumberFormat</a> does not seem to provide a way to do something like this either. So, what can you do instead?</p>
  
  <p>A straightforward way thanks to base 10 would be to insert a period at position -2 into the number string and pass that to the formatter:</p>
  
  <pre><code>let formatter = Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  })
  let s = (BigInt(10) + BigInt(20)).toString() // "30"
  s = s.padStart(2, "0")                       // zero-pad single digit (if input 0..9)
  s = s.slice(0, -2) + "." + s.slice(-2)       // ".30"
  formatter.format(s)                          // "$0.30"
  </code></pre>
  
  <p>Is this the way to go? Are there better solutions?</p>
  
  <p>I'm aware that <code>format(0.30000000000000004)</code> also results in <code>$0.30</code> because of rounding but this is rather a general question about BigInt + UI.</p>