2013-10-10 96 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; 
}