Formatting Currency in Javascript

I just had more trouble than I should have trying to figure out how to properly format currency, so it's going up as a blog post. Intl, the new feature available in modern browsers for internationaliztion, is actually really great for localizing and formatting things like currency, but here's to hoping this saves someone time digging through the spec.

Here's the code you want for USD:

var nf = new Intl.NumberFormat(‘en-US’, {
  style: ‘currency’,
  currency: ‘USD’,
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
nf.format(123456.789); // ‘$123,456.79’

The minimumFractionDigits and maximumFractionDigits options are what took me so long to find. When you format currency, at least for USD in English, you usually don’t want any more than 2 “cents” places displayed, or any less as well (it’s $3.50, not $3.5). These two options will ensure you always get 2 digits of cents.

If you'd like more info on Intl, NumberFormat, and what they can do, MDN explains this very thoroughly. I ran into this while using Formatjs, which has been great while doing fully featured internationalization with Handlebars. Lastly, keep in mind that Intl is shimmed if you need better browser support.