简体   繁体   中英

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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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