我正在尝试打印一个有两个小数位的数字,我需要用点作为数千个分隔符。
我不能使用.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);
您可以使用这个片段,它在大多数情况下都有效:
// 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,控制台