Javascript Add Commas to Number

  1. Use Regular Expressions to Format Number With Commas in JavaScript
  2. Use Intl.NumberFormat() to Format Number With Commas in JavaScript
  3. Use toLocaleString() to Format Number With Commas in JavaScript

This tutorial explains how we can print a number separated with commas in JavaScript.

We can use three different methods depending on our use-case and the speed/efficiency required in processing the given number.

Use Regular Expressions to Format Number With Commas in JavaScript

The regex uses two lookahead assertions:

  1. One positive lookahead assertion that searches for a point in the string containing a group of 3 digits after it.
  2. One negative lookahead assertion that makes sure that the given point has a group size of exactly 3 digits.

Then the replacement expression inserts a comma at that position.

It also takes care of the decimal places by splitting the string before applying the regex expression on the part before the decimal.

const numb=213231221;

function separator(numb) {
    var str = numb.toString().split(".");
    str[0] = str[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return str.join(".");
}

console.log(separator(numb))

Output:

"213,231,221"

Use Intl.NumberFormat() to Format Number With Commas in JavaScript

This method is used to represent numbers in language-sensitive formatting and represent currency according to the parameters provided. The parameter provided is called locale and specifies the format of the number. For example, The en-IN locale takes the format of India and the English language. The first comma from right separates thousands and rest onwards in terms of hundreds.

We will use the format() function attached to the object yielded by Intl.NumberFormat(). This function takes in the number and returns a comma-separated string. To achieve a string separated by thousand, we can use the en-US locale.

const givenNumber = 123423134231233423;

internationalNumberFormat = new Intl.NumberFormat('en-US')
console.log(internationalNumberFormat.format(givenNumber))

Output:

"123,423,134,231,233,420"

Use toLocaleString() to Format Number With Commas in JavaScript

The toLocaleString() method returns a string with the language-sensitive representation of a number just like the above method. It also takes the locales parameters that specify the format of the number.

const givenNumber = 123423134231233423;

console.log(givenNumber.toLocaleString('en-US'))

Output:

"123,423,134,231,233,420"

All the major browsers support all these ways.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Number

  • Generate a Random Number Between Two Numbers in JavaScript