add commas to a number in jQuery

I have these numbers

10999 and 8094 and 456

And all i want to do is add a comma in the right place if it needs it so it looks like this

10,999 and 8,094 and 456

These are all within a p tag like this <p class="points">10999</p> etc.

Can it be done?

I’ve attempted it here with the help of other posts but can’t seem to get it to work




Messed around a bit and managed to figure it out here

Going to look at the new Globalization plugin for a better way of doing it




Works on all browsers, this is all you need.

  function commaSeparateNumber(val){
    while (/(d+)(d{3})/.test(val.toString())){
      val = val.toString().replace(/(d+)(d{3})/, '$1'+','+'$2');
    return val;

Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:




However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to @baacke in the comments.

  function commaSeparateNumber(val){
   val = val.toString().replace(/,/g, ''); //remove existing commas first
   var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
   var valSplit = valRZ.split('.'); //then separate decimals
   while (/(d+)(d{3})/.test(valSplit[0].toString())){
    valSplit[0] = valSplit[0].toString().replace(/(d+)(d{3})/, '$1'+','+'$2');

   if(valSplit.length == 2){ //if there were decimals
    val = valSplit[0] + "." + valSplit[1]; //add decimals back
    val = valSplit[0]; }

   return val;

And in your jQuery, use like so:


Here’s the jsFiddle.