1
<script>
var START_DATE = new Date("January 01, 2013 00:00:00");
var INTERVAL = 0.25;
var INCREMENT = 0.001;
var START_VALUE = 0;
var count = 0;
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;
}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);
}
</script>
<div id="counter"> 30k</div>

我必须将 .toFixed(2) 放在哪里,以便我们的非营利组织的餐食柜台只显示小数点后两位。我尝试了许多不同的地方,但不确定 .toFixed 是否是正确的解决方案。请协助

4

3 回答 3

1

如果我运行:

count = 12345678.912;
formatted = count.toFixed(2).replace(/(\d)(?=(\d{3})+\.\d\d$)/g,"$1,");

格式化有字符串

12,345,678.91

作为它的价值。

我认为这可以满足您的要求,而且更简单。

于 2013-01-03T02:40:15.310 回答
1

把它放在你的addCommas函数中:

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,") + '.' + parseFloat(dec).toFixed(2).split('.')[1];
}
于 2013-01-03T02:44:44.880 回答
0

试试这个

function addCommasWithDecimal(nStr, decPlcs) {
    nStr = parseFloat(nStr).toFixed(decPlcs);
    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;
}
于 2013-01-03T02:41:33.083 回答