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.

Leave a Comment