Formatting a number with commas as thousands digit separators is something we do to make numbers easy to read.
In this article, we’ll take a look at how to format numbers with commas as thousands digit separators in JavaScript.
Replace with Regex
We can use the replace
method with a regex to add a comma every 3 digits.
To do this, we write:
const str = (1234567890).toString().replace(/B(?=(d{3})+(?!d))/g, ",");
console.log(str)
The B(?=(d{3})+
looks for groups of 3 digits before the decimal place.
The B
keeps replace
from adding a comma at the beginning of the string.
?=
is a lookahead assertion.
It means we only match 3 digits if the 3 digit pattern is followed by a non-word boundary.
?!
is a negative lookahead assertion.
It means we match the one-digit pattern only if it’s preceded by the 3 digit pattern.
So we make sure that we insert commas only if 3 digits are followed by another digit.
So we get ‘1,234,567,890’
as the value of str
The toLocaleString Method
The toLocaleString
method lets us format a number to a string with commas as thousands separators automatically.
For instance, we can write:
const str = (1234567890).toLocaleString()
console.log(str)
We call toLocaleString
directly on the number that we want to format.
So we get ‘1,234,567,890’
as the value of str
We can also set the locale to guarantee that the formatted value will always have the commas:
const str = (1234567890).toLocaleString('en-US')
console.log(str)
NumberFormat Constructor
We can also use the format
method of a NumberFormat
instance.
To use it, we write:
const nf = new Intl.NumberFormat();
const str = nf.format(1234567890);
console.log(str)
We create a Intl.NumberFormat
instance.
Then we call format
on the instance with a number.
Then we get the same result as the other examples.
Conclusion
We can add commas as thousands separators with a regex replace, or we can use formatter functions to do the same thing.