Formatting Currency Values in JavaScript

- 1 minute read

Did you know that JavaScript can save you from the burden of manually formatting currency values?

The built-in Internationalization API’s Number Formatter offers many useful methods.

Here is a basic example:

const num = 21489.524;

const dollars = new Intl.NumberFormat(`en-US`, {
    currency: `USD`,
    style: 'currency',
}).format(num);

In this example, dollars will return “$21,489.52”.

Pretty neat, right?

JavaScript inserts the specified currency symbol in the right place for us, which in this case, is USD.

It also adds commas and decimals based on the style (currency), and places them according to the localization code (en-US).

SIX maintains a list of supported currency codes. Localization codes are in BCP 47 format.

Here is one more example, using Euros and European formatting instead:

const num = 21489.524;

const euros = new Intl.NumberFormat(`fr-FR`, {
    currency: `EUR`,
    style: 'currency',
}).format(num);

This time, euros will return “21 489,52 €”.

Link to this section Conclusion

This is something I use quite often, and it’s saved me a lot of time.

I wish I knew about it sooner, and I hope you find it just as useful for formatting your monetary units on the fly!

Thanks for reading.