Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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.50

Other 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.50

Without 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,999

Storing 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.98

Common mistake

toFixed(2) only rounds; it adds neither the currency nor thousands separators:

console.log('$' + (1234.5).toFixed(2));

Output:

$1234.50

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.