This is a 2 min read · Published on 04 Jan 2022

Using JavaScript to format numbers is a very common task. The cool thing is, there are a lot of new built-in methods that make JavaScript format number a lot easier.

Let's take a look at three common strategies.

Format numbers with Regular expressions

The first thing we can try is using Regular Expressions. We can take any number, cast it to a string and then use the replace() method to add add a comma or decmial after every group of 3 numbers.

let number = 1000000000000
String(number).replace(/(.)(?=(\d{3})+$)/g, "$1,")

This returns '1,000,000,000,000'. And if you want decimals instead, change the last symbol to a period like so:

let number = 1000000000000
let result = String(number).replace(/(.)(?=(\d{3})+$)/g, "$1.")

This returns '1.000.000.000.000'.

JavaScript format number with toLocaleString

A better approach would be to use the built-in toLocaleString which returns language sensitive representations of numbers. We can simply:

let number = 1000000000000
let result = number.toLocaleString()

This will print '1.000.000.000.000'.

What's cool about this approach is, if you are using JavaScript to format money, you can pass in the user's country code and it will adapt. For example:

let number = 1000000000000
let result = number.toLocaleString("ja-JP", {
style: "currency",
currency: "JPY",
})

This will print '¥1,000,000,000,000'.

Format JavaScript numbers with NumberFormat

While toLocaleString is super clean and easy, it will slow down significantly when passing it large numbers. From MDN:

When formatting large numbers of numbers, it is better to create a Intl.NumberFormat object and use the function provided by its format property.

So, if we have a large number we need to format, we can use NumberFormat instead.

let number = 1000000000000
let result = new Intl.NumberFormat().format(number)

This will return '1,000,000,000,000'. The API is a little bit harder to use but you can still pass in all the country codes and formatting options that we used with toLocaleString. For example:

let number = 1000000000000
let result = new Intl.NumberFormat("ja-JP", {
style: "currency",
currency: "JPY",
}).format(number)

Which will return '¥1,000,000,000,000'.

Conclusion

Formatting JavaScript numbers used to be really hard. You had to write your own Regular Expression and cast your number to a string to use it. Now we have 2 great browser APIs for this task and they have a ton of flexibility.


Subscribe to my email list!

Let me be real with you. Sometimes when I'm bored I log in to Buttondown and look at the audience number. If it's bigger than it was the week before, well that makes me feel really happy! I promise I'll never spam you and I will, at most, send you a monthly update with what's happening on this site.