将逗号添加到setinterval计数器值

时间:2015-04-17 14:29:07

标签: javascript parseint

标题可能不是正确的,抱歉。

我试图为一个网站创建一个livecounter,这个想法是为了显示一个假的数字每秒都在增加。到目前为止我已经



var START_DATE = new Date("November 27, 2014 13:30"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 901; // initial value when it's the start date
var count = 0; //finally this shit is working

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);
}
   

<div id="counter"></div>
&#13;
&#13;
&#13;

这显示了一个像&#34; 24350919&#34;每秒增加,我想将其转换为24,350,919。我尝试使用parseFloat,但我无法使其正常工作。

有人可以帮我一把吗?谢谢!

2 个答案:

答案 0 :(得分:1)

修改: -

&#13;
&#13;
var START_DATE = new Date("November 27, 2014 13:30"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 901; // initial value when it's the start date
var count = 0; //finally this shit is working


window.onload = function() {
  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);
}

function addCommas(myStr)
{
    myStr += '';
    var x = myStr.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;
}
&#13;
<div id="counter"></div>
&#13;
&#13;
&#13;


您可以尝试使用toLocaleString(),如下所示:

var n = 24350919
n.toLocaleString()

在你的情况下就像

setInterval("count += INCREMENT; document.getElementById('counter').innerHTML =
         count;", msInterval.toLocaleString());

答案 1 :(得分:1)

尝试.toLocaleString()

msInterval.toLocaleString()