我正在使用以下脚本以一定间隔向上计数,它完美无缺。但是,我希望用逗号(56,181,995而不是56181995)格式化数字。
var START_DATE = new Date("July 27, 2010 13:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 101; // initial value when it's the start date
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}
我以为我在这里找到了答案,但我无法让它起作用:
How to print a number with commas as thousands separators in JavaScript
答案 0 :(得分:16)
(1234567890).toLocaleString();
答案 1 :(得分:12)
function addCommas(nStr)
{
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
http://www.mredkj.com/javascript/nfbasic.html
要整合:
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = addCommas(count);", msInterval);
答案 2 :(得分:2)
formatting - How can I format numbers as money in JavaScript?
使用此SO帖子格式化金钱作为基础,您可以重新设计此工作以进行逗号分离
这是一个例子 - http://jsfiddle.net/pxfunc/etfjW/
您可以扩展javascript Number
类型以包含commaSeparated
格式化程序方法,如下所示:
Number.prototype.commaSeparated = function() {
var n = this,
t = ",",
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0)) + "",
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);
};
然后像这样称呼它
count.commaSeparated();
或
(1234567890).commaSeparated();
答案 3 :(得分:2)
function addCommas(str){
var arr,int,dec;
str += '';
arr = str.split('.');
int = arr[0] + '';
dec = arr.length>1?'.'+arr[1]:'';
return int.replace(/(\d)(?=(\d{3})+$)/g,"$1,") + dec;
}