Number formatting (adding commas)

Hi Guys!

I was looking for a Javascript function to format numbers by adding commas for thousands etc. I want the function to run onBlur (i.e. when a user navigates away from a form input). The below function works, except if the user enters for example 1000000 and then navigates away from the form input and then goes back and adds an extra 0.

Does this make sense? Can anyone propose a fix?

Thanks!

function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\\d+)(\\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

Something like this? (Not tested).

function addCommas(nStr){
    nStr += '';
    c = nStr.split(','); // Split the result on commas
    nStr = c.join('');  // Make it back to a string without the commas
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\\d+)(\\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Thanks, works a treat! :slight_smile:

A little shorter version-

function addCommas(n) {
    n = String(n);
    var Rx = /^(.*\\s)?(\\d+)(\\d{3}\\b)/;
    return n == (n = n.replace(Rx, "$1$2,$3")) ? n : 
    addCommas(n);
}