Contents
JS Comma Separate Number – Not-Browser Compliant
In Javascript, it’s quite simple to convert a straight number to a number with thousands-place commas.
1 2 3 4 5 6 7 8 | var number = 1234; // number number.toLocaleString(); // Output (Most Browsers): // 1,234 // Output (Safari): // 1234 |
And if your number was a string, you can simply do something like this to make it work as well:
1 2 | var number = "1234" // string parseInt( number ).toLocaleString(); |
1 2 3 4 5 | // Output (Most Browsers): // 1,234 // Output (Safari): // 1234 |
As you can see above though, – it doesn’t work on Safari web browsers. That is true for both desktop and iOS mobile phones/tablets.

JS Comma Separate Number – Browser Compliant
To fix this, you need to create a slightly more complex formula, but it can still be done in one line if you’d like.
1 2 3 4 5 6 7 8 | var number = 1234; // number number.toString().replace(/.(?=(?:.{3})+$)/g, '$&,') // Output (Most Browsers): // 1,234 // Output (Safari): // 1,234 |
You could also create a function out of this if you’d like to make it a bit cleaner to reuse.
1 2 3 4 5 6 7 8 9 10 11 12 | function formatThousands(num) { return num.toString().replace(/.(?=(?:.{3})+$)/g, '$&,') } var number = 1234; // number formatThousands(number); // Output (Most Browsers): // 1,234 // Output (Safari): // 1,234 |
Lastly, of note – I didn’t come up with this magic – rather am documenting it here so that I (or others) could find this quickly/easily. The source of this solution (and a few other neat tips) can be found on the CSS Tricks website.
JS Comma Separate Number – Browser Compliant Handling Decimals
Added 2017-03-31
One other item of note is that the above function won’t handle decimal numbers. One tweak to the function and we can easily accomplish this however.
1 2 3 4 5 6 7 8 9 10 11 12 13 | function formatThousands(num) { var values = num.toString().split('.'); return values[0].replace(/.(?=(?:.{3})+$)/g, '$&,') + ( values.length == 2 ? '.' + values[1] : '' ) } var number = 1234.56; // number formatThousands(number); // Output (Most Browsers): // 1,234.56 // Output (Safari): // 1,234.56 |