How to format a price
Short answer
Intl.NumberFormat with style: 'currency' adds the currency sign, separators and two decimal places:
const price = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(price.format(1234.5));Output:
$1,234.50Other countries
The language sets where the sign goes and which separators are used:
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(1234.5));
console.log(new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' }).format(1234.5));Output:
1.234,50 €
€1,234.50Without cents
For whole amounts, set the number of decimal places to zero:
const price = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
console.log(price.format(1999));Output:
$1,999Storing in cents
To avoid rounding errors, shops often store prices in cents as integers and divide by 100 only for display:
const cents = 1999 + 2999;
const price = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(price.format(cents / 100));Output:
$49.98Common mistake
toFixed(2) only rounds; it adds neither the currency nor thousands separators:
console.log('$' + (1234.5).toFixed(2));Output:
$1234.50Functions used in this recipe
- Intl.NumberFormat — Formats numbers, currencies, percents and units by language rules.
- Number.prototype.toLocaleString — Formats a number by language rules: digit grouping, currency, percent.