2014-03-18 94 views
0

我試圖在我的20000之間添加一個逗號以顯示爲20,000,但沒有將它搞亂並且變得非常接近,但是試圖填充下一步。下面,我已經列出了我的代碼,它能夠完成它的功能,但試圖將兩者連接在一起以正常工作。如何通過JS在增加的數字中添加逗號?

Here is my jsFiddle!

和代碼..

HTML

<span id="liveNumbers">23000</span> 

JS

setInterval(function(){ 
random = (Math.floor((Math.random()*2)+1)); 
var plus = Math.random() < 0.5 ? 1 : 1; 
random = random * plus; 
currentnumber = document.getElementById('liveNumbers'); 

document.getElementById('liveNumbers').innerHTML = parseInt(currentnumber.innerHTML) + random; 

}, 3000); 

function commaSeparateNumber(val){ 
while (/(\d+)(\d{3})/.test(val.toString())){ 
    val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); 
} 
return val; 
    } 
+1

有人有相同的疑問,你http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Olvathar

+0

你應該只要能夠做一些像'console.log(commaSeparateNumber(currentnumber))',它應該做你想要的東西 – ntgCleaner

回答

2

你不得不改變你的初始值包含逗號或執行初始在setInterval開始之前運行,但是像這樣的東西可能會工作:

setInterval(function(){ 
    random = (Math.floor((Math.random()*2)+1)); 
    var plus = Math.random() < 0.5 ? 1 : 1; 
    random = random * plus; 
    currentnumber = document.getElementById('liveNumbers'); 
    var curnum = parseInt(currentnumber.innerHTML.replace(",","")); 

    document.getElementById('liveNumbers').innerHTML = 
     commaSeparateNumber(curnum + random); 
}, 3000); 

function commaSeparateNumber(val){ 
    while (/(\d+)(\d{3})/.test(val.toString())){ 
     val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); 
    } 
    return val; 
} 
+0

完美,謝謝。 – DoPeT