At times, I have had to add commas to numbers in order to make them look better in different applications. Even though there isn’t a native way to do this in JavaScript, the code can be quite short, sweet and to the point:

function addCommas(intNum) {
  return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}

The downside of the above function is that it will only work for integers. Here is a function that will get the job done for one number or a string which contains one or more numbers:

function delimitNumbers(str) {
  return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
    return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
  });
}

First this function forces the parameter that was passed in to become a string. Next, a global replace of a regular expression looking for a four-digit or longer number goes through and inserts the commas in the correct place. After that, the result is returned as a string.

Here are some tests that I ran on the function to make sure that it works correctly:

// Delimit a random number.
alert("Random number:  " + delimitNumbers(Math.random() * (1 << 30)));

// Delimit all powers of 2 (from 2^0 to 2^30) in a string.
var powersOf2 = Array.range(31).map(function(i){return 1 << i});
alert("Powers of 2:\n" + delimitNumbers(powersOf2.join("\n")));

Update

Updated on July 25, 2018:

This function is now available in YourJS which is a customizable JavaScript library allowing you to select which functions you want to include and the variable name by which you would like to reference the library. Here is the documentation for the corresponding commaNumber() function.


10 Comments

Brett Musick · July 25, 2011 at 12:15 AM

Rather educating blog, bookmarked the web page in interest to see a lot more!

Blake · October 14, 2011 at 11:52 PM

I’ve been searching for a simple solution for adding commas to numbers for the past hour. I’m so glad that I finally found your blog at the bottom of the hour. Your code is the only one I’ve seen that doesn’t use a for-while loop. I love it!!!

I’ve bookmarked your blog!

Gerald Fong · June 6, 2012 at 1:55 PM

One case where this doesn’t work very well is if you do delimitNumbers(1000.9999).

This will result in “1,000.999,9”

    Chris West · June 12, 2012 at 11:14 AM

    Good call! I just updated the function to only delimit the first part of a valid number (not one that starts with a zero or ends with multiple decimal points).

Nathan Long · June 21, 2012 at 7:58 PM

Nice results, but the code was hard to read. This seems to work the same and is clearer. Any cases I missed?

function addCommas(input){

var numberWithOptionalDecimal = /^(d+)(.?)(d+)$/g;

return (input.toString()).replace(numberWithOptionalDecimal, function(match, before, decimal, after) {
var insertCommas = function(string) { return string.replace(/(d)(?=(d{3})+$)/g, “$1,”); };
if (before == ‘0’) { return match; }
return decimal ? insertCommas(before) + decimal + after : insertCommas(before + after);
});
}

    Chris West · June 22, 2012 at 3:08 AM

    The major difference is the fact that yours works only if the argument passed in was originally a single number. Mine works for a string of one or more numbers. For instance, mine turns “1234.56 * 1234.56 = 1524138.3936” into “1,234.56 * 1,234.56 = 1,524,138.3936“. Also, I say that yours strictly works for a number being passed in because if I pass in “1000+1000” into yours, “1,000+1000” is returned. On the other hand, if you pass that same string into mine, “1,000+1,000” is returned as expected.

NT · July 16, 2014 at 5:30 PM

who would want to add commas like that… comma is decimal separator and thousands are separated by spaces… everyone knows that 🙂

    Chris West · July 17, 2014 at 1:09 PM

    The funny thing is I think many of us have had to work in environments where commas are in fact decimal separators and spaces are thousands spearators. In that case you can modify the function but I think most americans would be confused then (more confused than we already are 🙂 ).

Daniel · September 12, 2014 at 12:27 PM

Great little plugin–worked perfectly for me. Thanks!

Leave a Reply

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