JavaScript将货币转换为数千

javascript convert currency to thousands

本文关键字:转换 货币 JavaScript      更新时间:2023-09-26

我有一个十进制数*(28045.124578(*,我希望它被转换,以便它使用javascript以千种货币格式($28.0K(显示。

我正在使用这个脚本 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;

}

但这无济于事。请指教。

您可以使用 round 来获取最接近的整数。

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