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

3
  • 1
    seems rather complicated... Problem with your code is the fact it does not allow for leading zero. stackoverflow.com/questions/2901102/… Commented Nov 8, 2016 at 13:16
  • Can you use javascript function : toLocaleString() number =1.03; aa =number.toLocaleString(); console.log(aa); Commented Nov 8, 2016 at 13:20
  • Please refer this link it will solve your problem. Commented Nov 8, 2016 at 13:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.