3 Ways To Add Comma To Numbers In Javascript (Thousands Separator)

Welcome to a short tutorial on how to add commas to numbers in Javascript. So you have a project that needs to display some “nice-looking numbers”?

The easy ways to add commas to numbers in Javascript are:

  1. Use the toLocaleString() function
    • var num = 1234567.89;
    • var commas = num.toLocaleString("en-US");
  2. Convert the number to a string, and use a regular expression replace.
    • var commas = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

That covers the basics, but let us walk through more examples in this guide – Read on!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/add-comma-to-numbers-in-javascript/” title=”Add Comma To Numbers In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

ADD COMMAS TO NUMBERS

All right, let us now get into the examples of adding commas to a number in Javascript.

 

METHOD 1) LOCALE STRING

1-locale.html
// (A) THE NUMBER
var num = 1234567.89;
 
// (B) TO LOCALE STRING
console.log(num.toLocaleString("en-US")); // 1,234,567.89
console.log(num.toLocaleString("fr-FR")); // 1 234 567,89
console.log(num.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }));

As in the introduction, toLocaleString("en-US") is one of the easiest ways to add commas to a number. For beginners, that en-US fr-FR ja-JP is the language and locale code.

P.S. I have another tutorial to format the number as a currency, link below.

 

 

METHOD 2) REGULAR EXPRESSION REPLACE

2-replace.html
// CREDIT: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript
// (A) THE NUMBER 
var num = 1234567.89;
 
// (B) CONVERT TO STRING & REPLACE
var commas = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(commas); // 1,234,567.89

Once upon a time in the Dark Ages of the Internet, this is how we roll. Basically, convert the number into a string, then use a pattern (regular expression) to insert the commas. Not going into the details of how regular expression work, as it is a can of worms. But replace(/\B(?=(\d{3})+(?!\d))/g, ",") does the magic of inserting the commas.

 

 

METHOD 3) MANUAL INSERT COMMA

3-manual.html
// (A) ADD COMMAS TO SEPERATE GIVEN NUMBER
// num : original number
// per : add comma per n digits (default 3)
// places : number of decimal places (default 2)
function addComma (num, per, places) {
  // (A1) SET DEFAULTS
  if (per==undefined) { per = 3; }
  if (places==undefined) { places = 2; }

  // (A2) NO DECIMAL PLACES - ROUND OFF
  // REMOVE THIS IF YOU DON'T WANT TO ROUND OFF
  if (places==0) { num = Math.round(num); }
 
  // (A3) SPLIT WHOLE & DECIMAL NUMBERS
  var cString = num.toString(),
      cDot = cString.indexOf("."),
      cWhole = "", cDec = "";
  if (cDot == -1) {
    cWhole = cString;
    cDec = 0;
  } else {
    cWhole = cString.substring(0, cDot);
    cDec = cString.substring(cDot+1);
  }
 
  // (A4) ADD COMMAS TO WHOLE NUMBER
  var aComma = "", count = 0;
  if (cWhole.length > per) { for (let i=(cWhole.length-1); i>=0; i--) {
    aComma = cWhole.charAt(i) + aComma;
    count++;
    if (count == per && i!=0) {
      aComma = "," + aComma; 
      count = 0;
    }
  }} else { aComma = cWhole; }
 
  // (A5) ROUND OFF TO GIVEN DECIMAL PLACES
  if (places==0) { cDec = ""; }
  else {
    cDec = +("0." + cDec);
    cDec = cDec.toFixed(places).toString().substring(1);
  }
 
  // (A6) RETURN "WHOLE WITH COMMA" PLUS DECIMAL PLACES
  return aComma + cDec;
}
 
// (B) TEST
// (B1) WHOLE NUMBER
var whole = 123456789;
console.log(addComma(whole)); // 123,456,789.00
console.log(addComma(whole, 4, 0)); // 1,2345,6789

// (B2) DECIMAL
var dec = 23456.78;
console.log(addComma(dec)); // 23,456.78
console.log(addComma(dec, 2, 0)); // 2,34,57

Lastly, this is another manual alternative to adding commas to a number –

  • (A1) The “default settings” if none are provided.
  • (A2) Round off if 0 decimal places. Remove this line if you don’t want to round off.
  • (A3) Convert the number into a string, split it into the whole numbers and decimals.
  • (A4) Only add commas to the portion of the whole number.
  • (A5) Round off to the given number of decimal places.
  • (A6) Combine the whole and decimals back – Done!

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

SUMMARY

Function Description Link
NUMBER.toLocaleString() Format the number to the specified locale. Click Here
NUMBER.toString() Converts a number to a string. Click Here
STRING.replace() Replace all instances of a matched pattern in the string. Click Here

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

Add Comma To Numbers In Javascript (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

4 thoughts on “3 Ways To Add Comma To Numbers In Javascript (Thousands Separator)”

  1. Adds commas after the decimal for longer numbers.

    // (A) THE NUMBER
    var num = 1234.56789;
    // (B) CONVERT TO STRING & REPLACE
    var commas = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, “,”);
    console.log(commas); // 1,234.56,789

Leave a Comment

Your email address will not be published. Required fields are marked *