Add comma's to number in javascript

Published: {ts '2020-04-21 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/add-commas-to-number-in-javascript/

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; }