Safari浏览器中toLocaleString()的替代方法

4
我正在使用以下代码将数字转换为字符串:
ProductsData[0]['price'].toLocaleString();

我得到了预期的输出:
8,499

但是相同的代码在Safari中无法运行。

请给我一些建议......


“not working”?你有收到任何错误信息吗? - Cerbrus
没有错误,我得到的输出是8499,它应该像8,499一样。 - Preety Sapra
这只是一个整数值,从数据库获取并格式化后,我正在显示... - Preety Sapra
2个回答

0
尽管所有主流浏览器都支持没有参数的 `toLocaleString` 函数,但不幸的是,它在不同浏览器中的行为是不一致的。
如果一致的日期/时间格式很重要,恐怕你需要自己构建一个版本的 `toLocaleString` 函数或者使用一个库来处理。以下是几个值得调查的选择:

2
这里日期库是不相关的。 - Cerbrus

0
今天我在工作中遇到了这个问题,这个网站几乎每天都会使用这个功能,并偶然看到了你的问题(Safari浏览器无法显示货币或千位/小数点分隔符)。我编写了一个小的覆盖函数来解决toLocaleString的问题以适应我的需求(欧洲和欧元(€))。
希望这能帮助其他遇到同样问题的人。

(function() {
    Number.prototype._toLocaleString = Number.prototype.toLocaleString;
    Number.prototype.toLocaleString = function(locales,options) {
        if(options.style == "currency") {     // only format currencies.
            var prepend = "";
            if(options.currency == "EUR") {
            prepend = "\u20AC ";     // unicode for euro.
            }
            var val = this;
            val = val;
            
            // check if the toLocaleString really does nothing (ie Safari)
            
            var tempValue = val._toLocaleString(locales,options);
            if(tempValue == val.toString()) { // "broken"
            return prepend+val.formatMoney(2); // <-- our own formatting function.
            } else {
            return tempValue;
            }
        } else {
        return this._toLocaleString(locales,options);
        }
    };
    
    Number.prototype.formatMoney = function(c, d, t){
    var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "," : d, 
    t = t == undefined ? "." : t, 
    s = n < 0 ? "-" : "", 
    i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), 
    j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
     };
   
    // demonstration code
    var amount = 1250.75;
    var formattedAmount = amount.toLocaleString('nl-NL', {style:'currency',currency: 'EUR'});
    console.log(formattedAmount);

})();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接