如何在JavaScript

时间:2015-08-17 15:19:57

标签: javascript

为了使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
})();

......但这感觉就像是不必要的黑客。

1 个答案:

答案 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) : ",";

兼容性警告:

  • Safari出于某种原因可能不支持Intl对象 - http://caniuse.com/#feat=internationalization - 尽管它是标准ECMAScript的一部分。
  • 虽然某些ECMAScript标准浏览器中可能存在Intl对象,但以上代码仅适用于Chrome
  • 可悲的是,Firefox 40和IE 11目前在resolved中没有numFormat属性。

优雅的跨浏览器解决方案仍在那里......