4 Ways To Add Commas To Numbers In Javascript

Once upon a time, a confident student reassured Master Coffee that she can “add commas to a number in 5 minutes”. But after 5 minutes of research, she got more questions than answers. Yes, there are many ways to “add commas” in Javascript. Let Master Coffee walk you through with simple examples, let’s go.

 

CODE DOWNLOAD

I have released this under the MIT license, feel free to use it in your own project – Personal or commercial. Some form of credits will be nice though. 🙂

 

 

VIDEO TUTORIAL

 

METHOD 1) TO LOCALE STRING

1-locale.js
// (PART A) NUMBER
var num = 123456.98;

// (PART B) FORMAT NUMBER
console.log(num.toLocaleString("en-US"));
console.log(num.toLocaleString("en-US", { style: "currency", currency: "USD" }));

Let us start with one of the easier method, toLocaleString(LOCALE, OPTIONS).

  • LOCALE The first parameter is the locale. It’s set to “US English” here, with a comma for every 3 digits.
  • OPTIONS Optional options, things like format as currency, unit, percentage, etc… Too many to list here, check out the Number Format documentation on MDN.

 

 

METHOD 2) NUMBER FORMAT

2-format.js
// (PART A) NUMBER
var num = 123456.98;

// (PART B) FORMAT NUMBER
console.log(
  new Intl.NumberFormat("en-US")
  .format(num)
);
console.log(
  new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
  .format(num)
);

Now for the next method, create a new Intl.NumberFormat(LOCALE, OPTIONS) object and use it to format(NUMBER). As you can see:

  • LOCALE The same 2 digits language and country code as above.
  • OPTIONS The same set of options as above.

Yep, this kind of does the same thing as toLocaleString(), but in a slightly roundabout manner. If you just want to add commas to a number, stick with toLocaleString().

 

 

METHOD 3) REGULAR EXPRESSION

3-regex.js
// (PART A) NUMBER
var num = 123456.98;

// (PART B) FORMAT NUMBER
console.log(
  num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
);

For those who have not heard of “regular expression”, it’s simply a “search pattern” to match certain parts of a string. In this example:

  • num.toString() convert the number to a string first.
  • The pattern /\B(?=(\d{3})+(?!\d))/g will match every 3 digits.
  • Thus, replace(/\B(?=(\d{3})+(?!\d))/g, ",") will insert a comma for every 3 digits.

While this is a one-liner, writing a regular expression is “very inhuman”. How does one even come up with that pattern? Master Coffee has a “lazy hack”, just ask ChatGPT to “Write a Javascript regular expression to add a comma for every 3 digits”.

 

 

METHOD 4) MANUAL FORMAT

4-manual.js
// (PART A) FUNCTION TO ADD COMMAS
function commarize (num) {
  // (A1) SPLIT WHOLE & DECIMAL NUMBERS
  let split = num.toString().split("."),
  whole = split[0];

  // (A2) ADD COMMAS EVERY 3 DIGITS
  let every = 3;
  if (whole.length > every) {
    for (let i=whole.length-every; i>=0; i-=every) {
      if (i!==0) { whole = whole.slice(0,i) + "," + whole.slice(i); }
    }
  }

  // (A3) COMBINE & RETURN
  return split[1] ? whole + "." + split[1] : whole ;
}

// (PART B) FORMAT NUMBER
console.log(commarize(123456.98));

If all else fails, manual is the way to go. Do a quick trace and you will see what this does:

  • (A1) First, split into “whole number” and “decimal number”.
  • (A2) Manually loop through every 3 digits of the “whole number”, insert a comma.
  • (A3) Combine the “whole number” and “decimal number” back.

 

 

THE END – WHICH ONE TO USE!?

That’s all for this short tutorial. But before we end, most beginners will probably have one question – Which one should we use? Master Coffee will say “all of them works”.

  • If you want fuss-free, just use regular expression. Don’t have to deal with language code and country code.
  • Use locale string if you need flexibility in formatting as currency and units.
  • If you need “very specific rounding” or “quirky requirements”, manual is the way.

 

 

CHEAT SHEET

Ways To Add Commas In Javascript (click to enlarge)