Comma Separate Number in Javascript – Safari Compatiable

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.

And if your number was a string, you can simply do something like this to make it work as well:

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.

How to add a comma in the thousands place using Javascript so it's compatible with all browsers - including Safari.
How to add a comma in the thousands place using Javascript so it’s compatible with all browsers – including Safari.

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.

You could also create a function out of this if you’d like to make it a bit cleaner to reuse.

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.