简体   繁体   English

Javascript函数来格式化货币

[英]Javascript function to format currency

I am using the below function to generate formatted comma separated currency value in javascript but its not working for certain scenarios: 我正在使用以下函数在javascript中生成带格式的逗号分隔货币值,但在某些情况下不起作用:

1234 => 1,234 (correct)
1.03 => 1.3 (wrong)

how can i fix the issue in my below function: 我如何在以下功能中解决此问题:

function formatThousands(n, dp) {
    var s = '' + (Math.floor(n)), d = n % 1, i = s.length, r = '';
    while ((i -= 3) > 0) { 
        r = ',' + s.substr(i, 3) + r; 
    }
    return s.substr(0, i + 3) + r + (d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
}

Thanks in advance 提前致谢

To fix your code we need to make sure the rest has at least as much digits as the "dp" parameter, if not we will add leading zeros. 要修复您的代码,我们需要确保其余部分的位数至少与“ dp”参数的位数相同,否则,我们将添加前导零。

function formatThousands(n, dp) {
    var s = '' + (Math.floor(n)), d = n % 1, i = s.length, r = '';
    while ((i -= 3) > 0) { 
        r = ',' + s.substr(i, 3) + r; 
    }
    var rest = Math.round(d * Math.pow(10, dp || 2));
    var rest_len = rest.toString().length;
    if(rest_len < dp) {
        rest = '0'.repeat(dp - rest_len) + rest;
    }
    return s.substr(0, i + 3) + r + (rest ? '.' + rest : '');
}
console.log(formatThousands(1234.14, 2));       //1,234.14
console.log(formatThousands(1.003526, 4));      //1.0035

Anyway you could definitely find cleaner version of thousands separation as others mentioned in comments. 无论如何,您肯定可以找到注释中提到的数千分隔符的更干净版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM