DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Formatting Currency Values in JavaScript

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

This time, euros will return "21 489,52 €".

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.

Top comments (4)

Collapse
 
avngarde profile image
Kamil Paczkowski

Thanks man, it will speed up my app alot, as now im using third party api for currency conversion

Collapse
 
natclark profile image
Nathan

I'm so glad to hear that! Thanks for sharing.

Collapse
 
klutchkid profile image
Klutch

I love INTL!! Awesome write up!

Collapse
 
natclark profile image
Nathan

Thanks! Intl is pretty great.