DEV Community

Cover image for Add commas to numbers in JavaScript (Explained with examples)
Reza Lavarian
Reza Lavarian

Posted on • Originally published at decodingweb.dev

Add commas to numbers in JavaScript (Explained with examples)

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

This guide explores the three common ways to add commas to numbers in JavaScript.

Displaying numbers – whether currency or plain numbers – in an easy-to-read format significantly improves your HTML page content and overall user experience. We usually achieve this by adding commas to numbers with the help of JavaScript and separating the digits by hundreds.

There are plenty of ways to format your numbers. However, three of them are the most common among web developers:

  1. Using the Number.prototype.toLocalString() method
  2. Using Intl.NumberFormat() object
  3. Using String.prototype.replace() method with a regular expression

Let’s study each approach with examples.

Using Number.prototype.toLocalString()

The method Number.prototype.toLocalString() is the option you’re looking for if you need a quick solution. This method uses Int.NumberFormat() object internally to do language-sensitive number formatting (more on this below).

Here’s how we use it:

let number = 48372498372.34

console.log(number.toLocaleString())
Enter fullscreen mode Exit fullscreen mode

If you call it without arguments, it'll format the respective number based on the default locale - in this case, the US locale.

Some countries have their way of formatting numbers. For instance. in Germany, hundreds of separated by a period (".") and decimals with a comma. In that case, you can add the key as the first argument.

let number = 4723984738.5748937

console.log(Intl.NumberFormat('de-DE').format(number))
// output: 834.723.984.738,575
Enter fullscreen mode Exit fullscreen mode

You can fine-tune the output by passing it an options object. For instance, to display currency values.

let number = 834723984738.5748937

console.log(number.toLocaleString('en-US', { style: 'currency', currency: 'USD'}))
// output: ,723,984,738.58
Enter fullscreen mode Exit fullscreen mode

Note: when you set the style as currency, you must define the currency too. Otherwise, you'll get the following TypeError:

Uncaught TypeError: Currency code is required with currency style.
    at Number.toLocaleString (<anonymous>)
    at index.js:10:20
Enter fullscreen mode Exit fullscreen mode

The possible values for currency are ISO 4217 currency codes such as USD for the US dollar, EUR for the euro, or CNY for the Chinese RMB.

If you need to display decimal places with a fixed precision, you can define a minimumFractionDigits or maximumFractionDigits in the options object accordingly.

let number = 834723984738.5748937

console.log(number.toLocaleString('en-US', { style: 'currency', currency: 'EUR', minimumFractionDigits: 3}))
// output: €834,723,984,738.575
Enter fullscreen mode Exit fullscreen mode

Intl.NumberFormat()

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language-sensitive string comparison, number formatting, and the date and time formatting.

The Intl.NumberFormat() constructor creates Intl.NumberFormat objects that enable language-sensitive number formatting.

To format a number, you call the format() method against this object:

let number = 834723984738.5748937

console.log(Intl.NumberFormat('en-US').format(number))
// output: 834,723,984,738.575
Enter fullscreen mode Exit fullscreen mode

The output would be the same toLocalString() since it uses Intl.NumberFormat() internally (in implementations with Intl.NumberFormat API support).

And the options object is the same as the one in our toLocalString() code example:

let number = 834723984738.5748937

console.log(Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number))
Enter fullscreen mode Exit fullscreen mode

A note on performance, based on MDN docs:
When formatting a large set of numbers, it is better to create an Intl.NumberFormat object and use the function provided by its format property.

Using regular expression to add commas to numbers

Using regular expressions is the old-school way of handling number formatting. Even though toLocalString() and Intl.NumberFomat() is well-supported across most browsers, you might want to do it in an old-fashioned way.

To do this, you should use the String.prototype.replace() method with a regular expression that separates the hundreds by commas.

Let's see how it's done:

let number = 834723984738.5748937

console.log(number.toString().replace(/B(?=(d{3})+(?!d))/g, ','))
// output: 834,723,984,738.575
Enter fullscreen mode Exit fullscreen mode

The above code, first, converts your number into a string and then calls the replace method with this regex pattern /\B(?=(\d{3})+(?!\d))/g.

This regular expression starts with a boundary (\B) to avoid a comma at the beginning of the number. Then, it uses to lookaheads to mark numbers in hundreds. Consequently, The replace() method places a comma in each match.

Wrapping up

Formatting numbers can be done in a variety of ways in JavaScript. However, the approaches we explored in this quick guide are the most common among web developers:

  1. Number.prototype.toLocalString()
  2. Intl.FormatNumber from the ECMAScript Internationalization API
  3. Regular expressions

I hope this guide helps you find the answer you're looking for.

Thanks for reading.

Top comments (0)