2013-10-10 93 views
0

我有一個十進制數* (28045.124578) *我希望它被轉換,以便它將以千位貨幣格式($ 28.0K)使用javascript顯示。javascript將貨幣轉換爲數千

我使用這個腳本TP轉換,但這並不能幫助

function kFormatter(num) { 
num = num.toString().replace(/\$|\,/g, ''); 
if (isNaN(num)) 
{ 
    num = "0"; 
} 
num = Math.floor(num * 100 + 0.50000000001); 
cents = num % 10; 
num = Math.floor(num/100000).toString(); 
//console.log('num=', num/1000); 
if (cents < 10) 
{ 
    cents = "0" + cents; 
} 
for (var i = 0; i < Math.floor((num.length - (1 + i))/3); i++) 
{ 
    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3)); 
} 

return num + '.' + cents; 

}

,但是這並不能幫助。請建議。

+1

http://josscrowcroft.github.io/accounting.js/ – Ramunas

+0

沒有js庫請!!!我想要一個自定義函數來做到這一點。 –

+0

您能否更具體地瞭解預期結果?對於最簡單的解決方案'Math.round(num/100)/ 10;'會給你結果 – Ramunas

回答

0

你可以用round來得到最接近的整數。

function kformatter(num){ 
    var newvalue = Math.round(num/100); 
    return newvalue?(newvalue/10)+"K":num; 
}