2016-07-29 71 views
-3

我试图打印一个有两位小数的数字,我需要将它作为千位分隔符。如何用javascript格式化数字(以Safari的方式工作)

我不能使用.toLocaleString(),因为它不会在Safari工作...

这里是我的代码:

var currentTime; 

    if (localStorage['time']) { 
     currentTime = Number.parseFloat(localStorage['time']); 
    } 
    else { 
     currentTime = 0; 
    } 

    var container = document.getElementById('count'); 

    setInterval(function() { 
     currentTime += .01; 
     container.innerHTML = currentTime.toFixed(2); 
     //container.innerHTML = currentTime.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}); 
     localStorage['time'] = currentTime; 
    }, 100); 
+0

这里有一个关于这个常见问题的深入答案http://stackoverflow.com/a/149099/280842 – Filype

+0

可能的重复[如何将数字格式化为JavaScript中的金钱?] (http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) – jmoerdyk

回答

0

您可以使用此代码片段在大多数情况下工作:

// source: http://stackoverflow.com/a/149099/280842 
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 = parseInt(n = Math.abs(+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) : ""); 
}; 

使用它:

(123456789.12345).formatMoney(2, '.', ','); 

工作示例:https://jsbin.com/nuyinatuju/edit?js,console