Formatting numbers as currency stings is something that we have to do sometimes in our JavaScript apps.
In this article, we’ll look at how to format numbers as currency strings with JavaScript.
The Intl.NumberFormat Constructor
We can use the Intl.NumberFormat
constructor that comes with most browsers to format a number into a currency string.
For instance, we can write:
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
const str = formatter.format(1500);
console.log(str)
We pass in the locale and an object with formatting options arguments of the constructor.
style
is set to 'currency'
to format a number into a currency string.
currency
is set to 'USD'
to let us format it the number into USD format.
Then we just call format
with the amount and assign the result to str
.
And so str
is ‘$1,500.00’
.
We can also set the minimumFractionDigits
and maximumFractionDigits
properties in the object to set the min and max number of decimal places to return.
toLocaleString
JavaScript strings come with the toLocaleString
method that lets us format numbers into currency strings.
For instance, we can write:
const str = (1500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
});
console.log(str)
The arguments are the same as the format
method.
And we get the same result as Intl.NumberFormat
.
Intl.NumberFormat
is 70 times faster than toLocaleString
if we have lots of numbers to format, so it’s better to use Intl.NumberFormat
if we need to format lots of numbers.
Regex Replace
We can use the toFixed
method to return a string with 2 decimal places.
Then we can use replace
to add thousands separators to the returned string.
For instance, we can write:
const str = (123.45).toFixed(2).replace(/d(?=(d{3})+.)/g, '$&,');
The ?=
is a lookahead assertion to let us get groups of 3 digits in a string behind one digit.
So if it sees groups of 3 digit behind another digit, then it’ll add a comma in between the digits.
$&
indicates that we want to do the replacement in the existing string and not replace characters.
Therefore, str
should be '123.45'
.
Conclusion
We can format numbers into currency strings with JavaScript by using built-in methods.
Also, we can use the replace
method to add commas between groups of 3 digits.