In order for toLocaleString to work, the browser/JavaScript must know the user's locale and whether or not the specific locale uses "," or "." for a thousands separator. Is it possible to access this data so that we can determine what the thousands separator is?
If not, we can use a function like this...
var thousandsSeparator = (function(){
if (typeof Number.prototype.toLocaleString === 'function') {
var num = 1000;
var numStr = num.toLocaleString();
if (numStr.length == 5) {
return numStr.substr(1, 1);
}
}
return ","; // fall-back
})();
...but it feels like an unnecessary hack.
A little further digging and I found Intl.NumberFormat. I think this is more elegant...
const thousandsSeparator = (function(){
if (typeof Intl !== 'object') {
return ','; // fallback
}
// Get the formatting object for your locale
const numFormat = new Intl.NumberFormat();
// The resolved.pattern will be something like "#,##0.###"
return numFormat.resolved.pattern.substr(1,1);
})();
Or if you really need it ultra-concise...
const thousandsSeparator = (Intl) ? (new Intl.NumberFormat()).resolved.pattern.substr(1,1) : ",";
Compatibility warning (2015):
Intl
object may not be supported in Safari for some reason -- http://caniuse.com/#feat=internationalization -- despite it being part of standard ECMAScript.Intl
object may exist in some ECMAScript-standard browsers, the code above will only work in Chrome.resolved
property in numFormat
.An elegant cross-browser solution is still out there...
Update (2021):
Intl
, and numFormat.resolved
may have better browser support in non-Chrome browsers now. See comments for latest information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With