How to Format a Number as a Currency in JavaScript

Updated onbyAlan Morel
How to Format a Number as a Currency in JavaScript

Because of how different each country/region formats it, properly formatting a currency from a number is difficult.

For example, in the US, a comma is used to separate the thousands, but in France, a dot is used to separate the thousands.

In this post, we'll learn the proper way to convert a number to a currency.

Converting a number to a currency

First let's start out with our value:

JAVASCRIPT
const value = 25;

Let's say we want to be able to convert this to $25.00. The best way to do this is to use JavaScript's internationalization API.

Included in this API is a number formatter that supports currency.

Let's define a number formatter that we can use to format 25 into $25.00.

JAVASCRIPT
const formatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 });

Now, using this formatter object, we just need to call the format function and pass in the number you want to format.

JAVASCRIPT
const value = 25; const formatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 }); const formatted = formatter.format(value); console.log(formatted);
BASH
$25.00

The style property is used to designate that we want to format the number as a currency.

The currency property is used to specify the currency, in this case, it's USD.

The minimumFractionDigits property is used to specify the minimum number of digits after the decimal, which for currencies is usually 2.

The cool part about this API is that switching to euros in France is as simple as changing the currency property to EUR and en-US to fr-FR.

JAVASCRIPT
const value = 25; const formatter = new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR", minimumFractionDigits: 2 }); const formatted = formatter.format(value); console.log(formatted);
BASH
25,00 €

This API and number formatter takes the hard work out of formatting currencies for you.

Conclusion

In this post, we learned how to convert a number to a currency.

Simply invoke the format function from the Intl.NumberFormat object and pass in the number you want to format.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.