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?

  • 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) – ChrisG 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. – ChrisG 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)));
ProGu
  • 5,250
  • 1
  • 2
  • 11
1

You can use maximumFractionDigits

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