0

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Asif Iqbal
  • 531
  • 8
  • 28
  • 1
    seems rather complicated... Problem with your code is the fact it does not allow for leading zero. http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript?answertab=votes#tab-top – epascarello Nov 08 '16 at 13:16
  • Can you use javascript function : toLocaleString() number =1.03; aa =number.toLocaleString(); console.log(aa); – Azeez Kallayi Nov 08 '16 at 13:20
  • Please refer this [link](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) it will solve your problem. – Husen Nov 08 '16 at 13:24

1 Answers1

1

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.

Ales Trunda
  • 169
  • 1
  • 5