How to format numbers as currency strings
I was working on a project that has to display currency in the UI for different parts of the world.
Here are a couple solutions that helped me:
Okay solution: use Number.toFixed(2
)
This solution is okay if the currency you’re using has 2 decimal places. Not all currencies have 2 decimal places.
(2500).toFixed(2) // '2500.00'
// Or
Number(2500).toFixed(2) // '2500.00'
// No good
2500.toFixed(2) // Uncaught SyntaxError: Invalid or unexpected token
All Number.toFixed(2)
is just convert a number into a string with 2 decimal places. You can also see in the example above that you’ll need to wrap the integer with the Number
constructor or parenthesis.
Let’s look at an example with a lot of decimals places.
(2500.13602).toFixed(2) // '2500.14'
Number.toFixed(2)
will trim after the second decimal place and round to the nearest hundredth.
Now to add a currency, I would just concatenate the string with the currency symbol.
`$${(2500).toFixed(2)}` // '$2500.00'
This is an okay solution, but not optimal. You can also see that you’ll need to add the comma (,
) manually.
Let’s look at a solution that is better!
Best solution: Intl.NumberFormat()
All modern browsers support JavaScripts native Intl
API–which stands for Internationalization API.
We can use this API to create currency output strings. Here’s an example!
const { format } = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
Intl.NumberFormat()
accepts 2 arguments. The first argument is the locale, and the second argument is an object with other options that you can set.
Since I want to create currency string outputs, I will set the style
as currency
and the currency
parameter as the desired currency output.
Once you’ve initiated the new Int.NumberFormat()
you will be given access to a function called format()
which is where you will enter your integer value in to get the currency string.
const { format } = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
// Positive number
format(2500) // '$2,500.00'
// Negative number
format(-2500) // '-$2,500.00'
// Multiple decimal places
format(2500.1356) // '$2,500.14'
Extra: Get locale dynamically
You can use the navigator.language
global variable to get a dynamic locale.
new Intl.NumberFormat(navigator.language, opts);
I like to tweet about JavaScript and post helpful code snippets. Follow me there if you would like some too!