0

i have to do a task that make a number separates every thousands with commas and maximum 6 number after 'dot' in js. For examples

12345678.1234567 -> 12,345,678.123457 (need to round)
12345678.1234533 -> 12,345,678.123453
12345678.12      -> 12,345,678.12
12345678.0       -> 12,345,678

I tried with some localeString and toFixed

Number(number.toFixed(6)).toLocaleString("en-US");

but always face some exceptions and i do not how to round after dot also. What should i do?

sonphung.xf
  • 107
  • 8
  • Can you show us the code you've tried? Also, please try to look for existing solutions first, like [this rounding question](https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary) –  Dec 22 '21 at 08:58
  • @ChrisG i updated my question and i am also get the idea from your suggest question, but it seems like i did something wrong – sonphung.xf Dec 22 '21 at 09:09
  • `toLocaleString()` supports options; you can use those to force 6 decimals. –  Dec 22 '21 at 09:15

2 Answers2

2

Try Intl.NumberFormat()

const numbers = [12345678.0, 12345678.12, 12345678.123456, 12345678.1234567];
const f = new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 });

numbers.forEach(n => console.log(f.format(n)));
ProDec
  • 5,390
  • 1
  • 3
  • 12
1

You can use maximumFractionDigits

var number = 12345678.1234567;
const formatted = number.toLocaleString("en", {   
   minimumFractionDigits: 0,
   maximumFractionDigits: 6,
});
console.log(formatted);
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24