Home > Net >  How to format a number in js with maximum 6 number after comma
How to format a number in js with maximum 6 number after comma

Time:12-22

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?

CodePudding user response:

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)));

CodePudding user response:

You can use maximumFractionDigits

var number = 12345678.1234567;
const formatted = number.toLocaleString("en", {   
   minimumFractionDigits: 0,
   maximumFractionDigits: 6,
});
console.log(formatted);

  • Related