The Number toLocaleString() method
By Flavio Copes
Learn how the JavaScript Number toLocaleString() method formats a number according to a locale, so you can show it in US, Italian, or Arabic conventions.
toLocaleString() formats a number according to a locale. The same number comes out with different decimal separators, different thousands separators, even different digits, depending on the locale you ask for.
Called with no arguments, it uses the default locale of the environment your code runs in. On my machine, set to US English, I get:
(21.2).toLocaleString() //21.2
We can pass the locale as the first parameter. Italian uses a comma as the decimal separator:
(21.2).toLocaleString('it') //21,2
This is Eastern Arabic, which uses its own digits:
(21.2).toLocaleString('ar-EG') //٢١٫٢
Thousands separators
The differences show up even more with big numbers. US English separates thousands with commas. German does the opposite: dots for thousands, comma for decimals.
(1234567.891).toLocaleString('en-US') //1,234,567.891
(1234567.891).toLocaleString('de-DE') //1.234.567,891
Same number, and the dots and commas swap meaning. This is why you want a formatting function instead of building the string yourself.
Formatting options
The second parameter is an options object. The most useful one is currency formatting:
(21.2).toLocaleString('it', { style: 'currency', currency: 'EUR' }) //21,20 €
You can format percentages. The value gets multiplied by 100 and the sign is added:
(0.15).toLocaleString('en-US', { style: 'percent' }) //15%
And you can limit the decimal digits:
(3.14159).toLocaleString('en-US', { maximumFractionDigits: 2 }) //3.14
There are a number of other options, and I suggest to look at the MDN page to know more.
You can also try locales and options live in my free Intl.NumberFormat playground.
Watch out for the default locale
Here’s the mistake I see most often: relying on the default locale. Your machine is set to en-US, so everything looks right in development. Then a user in Italy opens the page and every number is formatted differently. If the format matters, pass the locale explicitly.
One more thing. The output is a string, meant for display. Don’t do math with it, and don’t try to parse it back into a number. parseFloat('21,2') gives you 21, because it stops at the comma. Keep the number for calculations, and format it only when you show it.
Related posts about js: