2013-01-03 54 views
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甚至是正確的解決方案。請協助Javascript用餐計數器.toFixed加上逗號

回答

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]; 
} 
+0

內計數我想這第二個,它是一個卓越和快速的解決方案! – LiQuiD

1

如果我運行:

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

格式有串

12,345,678.91 

爲它的價值。

我認爲這是你想要的,更簡單一些。

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; 
} 
+0

我嘗試這樣做第一,但它並沒有呈現在div – LiQuiD