Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to format a number with thousands separators

Short answer

The toLocaleString() method formats a number using the rules of a given language:

console.log((1234567.891).toLocaleString('en-US'));

Output:

1,234,567.891

Decimal places

The second argument sets the precision:

console.log((1234.5).toLocaleString('en-US', { minimumFractionDigits: 2 }));

Output:

1,234.50

Currency

The currency style puts the currency sign in the right place:

console.log((1234.5).toLocaleString('en-US', { style: 'currency', currency: 'USD' }));

Output:

$1,234.50

Short form

The compact notation turns large numbers into 1.2K or 3.4M:

const short = new Intl.NumberFormat('en-US', { notation: 'compact' });
 
console.log(short.format(1234), short.format(3400000));

Output:

1.2K 3.4M

Common mistake

Without a language argument, toLocaleString() uses the language of the user's system, so the result differs from computer to computer. Pass the language explicitly:

console.log((1234567.5).toLocaleString('en-US'));
console.log((1234567.5).toLocaleString('de-DE'));

Output:

1,234,567.5
1.234.567,5

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.