Add comma's to number in javascript

Author: Steven Neiland
Published:

I thought I would switch it up this week with a little JS-101.

Here is a utility function I've had around for formatting numbers into comma separated strings. Since it uses a some regex I thought it might be of interest to someone who is just getting started with regular expressions.

function addCommas(num){
      num = num.toString(); // Cast to a string so we can manipulate it
      var numberSplit = num.split('.'); // Split the string into a whole number and decimal
      var wholeNumber = numberSplit[0];

      // If there is a decimal then create a string representation including a decimal point
      var decimalComponent = numberSplit.length > 1 ? '.' + numberSplit[1] : '';

      // Working from the end of the number string backwards
      // capture numbers in groups of three where there is at least
      // one other number before the grouping
      var regularExpression = /(\d+)(\d{3})/;
      while (regularExpression.test(wholeNumber)) {
            // Insert the comma between the first group of numbers of unknown length
            // and the immediate group of three numbers after it
            wholeNumber = wholeNumber.replace(regularExpression, '$1' + ',' + '$2');
      }

      return wholeNumber + decimalComponent;
}

What Do You Think?

Reader Comments

Comment Etiquette:

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain or appear to be advertisments, will not be published.
  • Comments that appear to be created for the purpose of linkbuilding to commercial sites will be removed.
*
*



Archives Blog Listing