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.891Decimal places
The second argument sets the precision:
console.log((1234.5).toLocaleString('en-US', { minimumFractionDigits: 2 }));Output:
1,234.50Currency
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.50Short 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.4MCommon 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,5Functions used in this recipe
- Number.prototype.toLocaleString — Formats a number by language rules: digit grouping, currency, percent.
- Intl.NumberFormat — Formats numbers, currencies, percents and units by language rules.