在Javascript Countup中添加逗号

时间:2018-03-13 12:26:08

标签: javascript

我有这个Javascript

<script>
var START_DATE = new Date("February 21, 2018 00:00:00"); // put in the 
starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 6720; // increase per tick
var START_VALUE = 17419171608; // 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);
}
</script>

我试图用逗号分隔上面代码中的数千个但我无法这样做。

我尝试了here的说明,但是我无法用逗号分隔数千个。

非常感谢任何帮助。感谢。

3 个答案:

答案 0 :(得分:1)

您可以尝试在&#34; count&#34;上使用Number.prototype.toLocaleString()函数。变量。将根据区域设置打印该编号,因此对于EN,它将具有预期的逗号。

var count = 10000000;    
console.log (count.toLocaleString());

答案 1 :(得分:1)

检查出来:How to print a number with commas as thousands separators in JavaScript

解析负数,大数和浮点数有很好的功能。

您可以尝试在执行此操作后输出您的计数:

const numberWithCommas = (x) => {
  var parts = x.toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
}

这是一个快速的小提琴我一起向你展示方法: https://jsfiddle.net/r4s5rrrn/2/

答案 2 :(得分:1)

我举了你的例子,我修改了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <script type="text/javascript">
 
            var START_DATE = new Date("December 1, 2010 20:00:00"); // put in the starting date here
            var INTERVAL = 1; // in seconds
            var INCREMENT = 1; // increase per tick
            var START_VALUE = 4166667; // 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 = addCommas(count.toString());
                setInterval(incrCount, msInterval);
            }
 
            function incrCount() {
                count += INCREMENT;
                document.getElementById('counter').innerHTML = addCommas(count.toString());
            }
 
           
			
			function addCommas(nStr){
                return parseInt(nStr).toLocaleString();
            }
        </script>
    </head>
    <body>
 
        <div id="counter"></div>
 
    </body>
</html>