how to print number with commas as thousands separators in Javascript
- by mikez302
I am trying to print an integer in Javascript with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this? Here is how I am doing it:
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
I am wondering if anyone has a simpler or more elegant idea. It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas.