Prototyping function to add commas to numbers

Thanks to my predecessor Mike Grace for this helpful little script. It extends javascript to add the correct comma places to any number. Number.prototype.addCommas = function() { var nStr =…

Thanks to my predecessor Mike Grace for this helpful little script. It extends javascript to add the correct comma places to any number.

Number.prototype.addCommas = function() {
	var nStr = this + ''; // convert number to string
	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;
};

Usage:

var item = 250435;
item.addCommas(); //changes number to 250,435