How to Use Comma as Thousand Separator in JavaScript

Comma as a thousand separator in Python

To comma-separate thousands in a big number in JavaScript, use the built-in toLocaleString() method.

It localizes the number to follow a country-specific number formatting. To separate thousands with commas, localize the number to the USA. To do this, pass the ‘en-US’ locale code as an argument to the toLocaleString() method.

For example:

const n = 716298462;
const formatted = n.toLocaleString('en-US');

console.log(formatted)

Output:

716,298,462

Alternative Approaches

The toLocaleString method works fine. It is still worthwhile to notice there are 2 other ways you to comma-separate thousands in a number in JavaScript.

  1. Intl.NumberFormatter() object.
  2. Custom function

Let’s briefly introduce these approaches.

Intl.NumberFormatter

In JavaScript, there is an internationalization namespace called Intl. This provides you with ways to be language-sensitive in:

  • String comparison.
  • Number formatting.
  • Date formatting.

You can thus use this namespace to format numbers for different localizations. To do this, use the Intl.NumberFormat() object by providing it the localization code. In case you want to use commas as thousand separators, use the en-US.

For example:

const n = 716298462;

const numberFormatter = Intl.NumberFormat('en-US');
const formatted = numberFormatter.format(n);

console.log(formatted)

Output:

716,298,462

Custom Thousand-Separating Function

Meanwhile, I suggest using a built-in function to comma-separate thousands. But you may also write a custom implementation to practice your RegEx skills.

To implement your own thousand-comma-separator function, you need to:

  • Convert the number to a string.
  • Split a digit to a number part and a possible decimal part.
  • Use RegEx to find the thousands (groups of 3 digits) in the number part and add a commas in-between.
  • Separate the number and the decimal part with a dot.

Here is how it looks in code:

function commify(n) {
    var parts = n.toString().split(".");

    const numberPart = parts[0];
    const decimalPart = parts[1];
    const thousands = /\B(?=(\d{3})+(?!\d))/g;

    return numberPart.replace(thousands, ",") + (decimalPart ? "." + decimalPart : "");
}

Output:

commify(9010173.1293) // Returns '9,010,173.1293'

In case you are interested in details, let’s take a look at the RegEx part, /\B(?=(\d{3})+(?!\d))/g; , a bit closer.

RegEx Part Explained in Detail

If you are wondering what RegEx is, it means Regular Expression. It is a pattern-matching technique used broadly across developers when looking for matching words. It is like a CTRL-F on steroids. Not only can you match with exact words, but also words with a specific format, such as email addresses or phone numbers.

To learn more about RegEx, check this guide.

For someone familiar with RegEx, in this example, the regular expression thousands = /\B(?=(\d{3})+(?!\d))/g:

  • /…/g creates a regular expression that matches all the occurences of a pattern.
  • \B means do not match the beginning of the number string.
  • (?=(…)) does a positive lookahead. The captured match must be followed by what is specified inside the parenthesis, but that part is not captured.
  • (\d{3}) captures three digits.
  • (?!\d) does a negative lookahead. It matches with something not followed by a digit.

So \B(?=(\d{3})+(?!\d)) checks that one or more groups of exactly three digits follows, but ensures no additional digits follow that.

For instance, if you use this regular expression on 987654321.00:

Every point left to 3 is matched by the positive lookahead as 321 is 3 digits in length. The negative lookahead then checks that the multiple of 3 digits does not have any digits after it.

  • 321 is followed by a period. It is a group of 3 digits so a comma goes there.
  • But 432 is also multiple of 3 digits. However, it is followed by by 1 from the earlier group, so commas inserted.
  • 543 is also 3 digits in length. But it is followed by 2 and 1 from the earlier group. No commas necessary.
  • 654 is 3 digits in length followed by 321, which is the whole earlier match group. Thus a comma is inserted here.
  • This process continues all the way to the beginning of the digit.

The result will be 987,654,321.00

Conclusion

Today you learned how to separate thousands with commas in a big number in JavaScript.

To recap:

  • You can use the toLocaleString() method to comma-separate thousands in a number for a given localization, such as ‘en-US’.
  • You can also use the Intl.NumberFormatter object to format a number to a specific localization.
  • Lastly, you can also build your own custom function to get the job done.

Thanks for reading.

Happy coding!

Further Reading

100 JavaScript Interview Questions

50+ Web Development Buzzwords

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.