Format a number with comma as a thousands separator in JS
Let's inspect how to do this with toLocaleString() and Intl.NumberFormat().format()
By: Ajdin Imsirovic 12 January 2021
RegExp might be the first thing that comes to mind when formatting numbers to include commas as thousands separators. However, there are other built-in ways to do this in JavaScript.
Here’s an example with a toLocaleString()
method:
It works with decimal numbers too:
1
2
3
4
5
(function() {
let floatingPoint = 1234567890.50;
console.log(floatingPoint.toLocaleString());
})()
// 1,234,567,890.5
Obviously, the above code converts our number into a string, using the local language. The language is determined by the locale language of our machine’s operating system. However, it’s enough to pass the locale data to change that. For example:
1
2
3
4
5
(function() {
let floatingPoint = 1234567890.50;
console.log(floatingPoint.toLocaleString('de-DE'));
})()
// 1.234.567.890,5
As an alternative solution, we can use the Intl
constructor function. The Intl
namespace exposes JS’s Internationalization API. The Intl
object comes with various methods for formatting numbers, dates, and times, as well as string comparison. Here’s the list of constructors:
Intl.Collator()
Intl.DateTimeFormat()
Intl.DisplayNames()
Intl.ListFormat()
Intl.Locale()
Intl.NumberFormat()
Intl.PluralRules()
Intl.RelativeTimeFormat()
Intl.getCanonicalLocales()
(a static method; i.e we can use it without the constructor function)
With Intl
, we can format a number in a country-specific way. Additionally, we can format anything else related to localization, such as dates. For now, let’s stick to the task at hand, which is number formatting:
1
2
3
4
5
(function() {
const number = 123456789;
console.log(Intl.NumberFormat('en-US').format(number));
})()
// 123,456,789
Let’s try the de-DE
locale:
1
2
3
4
5
(function() {
const number = 123456789;
console.log(Intl.NumberFormat('de-DE').format(number));
})()
// 123.456.789
Here’a a more robust function that we can use to convert to different locales:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function localeConverter() {
var number = prompt('Enter a number');
var country = prompt('Type EN, DE, or FR').toUpperCase();
if(country == 'EN') {
var locale = 'en-US';
console.table(
`${new Intl.NumberFormat(locale).format(number)}`
)
}
if(country == 'DE') {
var locale = 'de-DE';
console.table(
`${new Intl.NumberFormat(locale).format(number)}`
)
}
if(country == 'FR') {
var locale = 'fr-FR';
console.table(
`${new Intl.NumberFormat(locale).format(number)}`
)
}
}
localeConverter();
As mentioned ealier, yet another alternative solution for this exercise is to use RegExp, but we’ll leave RegExp implementations for another time.
Note:
This exercise comes from Book 3
of my book series on JS, available on Leanpub.com.