add commas to a number in jQuery

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:

$('#elementID').html(commaSeparateNumber(1234567890));

or

$('#inputID').val(commaSeparateNumber(1234567890));

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
   }else{
    val = valSplit[0]; }

   return val;
  }

And in your jQuery, use like so:

$('.your-element').each(function(){
  $(this).html(commaSeparateNumber($(this).html()));
});

Here's the jsFiddle.


Number(10000).toLocaleString('en');  // "10,000"

Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.

      $('#textfield').live('keyup', function (event) {
        var value=$('#textfield').val();

      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var newvalue=value.replace(/,/g, '');   
      var valuewithcomma=Number(newvalue).toLocaleString('en');   
      $('#textfield').val(valuewithcomma); 

      });

    <form><input type="text" id="textfield" ></form>

Take a look at recently released Globalization plugin to jQuery by Microsoft