为了使toLocaleString能够正常工作,浏览器/ JavaScript必须知道用户的区域设置以及千位分隔符是否the specific locale uses "," or "."。是否可以访问这些数据,以便我们确定千位分隔符是什么?
如果没有,我们可以使用这样的函数......
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
})();
......但这感觉就像是不必要的黑客。
答案 0 :(得分:4)
进一步挖掘,我发现Intl.NumberFormat。我觉得这更优雅......
var thousandsSeparator = (function(){
if (typeof Intl === 'object') {
// Gets the formatting object for your locale
var numFormat = new Intl.NumberFormat();
// The resolved.pattern will be something like "#,##0.###"
return numFormat.resolved.pattern.substr(1,1);
}
return ",";
})();
或者如果你真的需要超简洁......
var thousandsSeparator = (Intl) ? (new Intl.NumberFormat()).resolved.pattern.substr(1,1) : ",";
兼容性警告:
Intl
对象 - http://caniuse.com/#feat=internationalization - 尽管它是标准ECMAScript的一部分。Intl
对象,但以上代码仅适用于Chrome 。 resolved
中没有numFormat
属性。 优雅的跨浏览器解决方案仍在那里......