本文介绍了将逗号添加到JavaScript输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下脚本以一个间隔向上计数,它运行良好.但是,我希望用逗号将数字格式化(56,181,995,而不是56181995).
I'm using the following script to count upward at an interval and it works perfectly. However, I'd like it to format the number with commas (56,181,995 instead of 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);
}
我以为我在这里找到了答案,但我无法使它起作用:
I thought I had found an answer here on SO but I can't get it to work:
推荐答案
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);
这篇关于将逗号添加到JavaScript输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!