Formatting number as a currency in JavaScript

Piotr Pliszko

To format number as a currency, you can use JavaScript Internationalization API. It’s accessible with Intl object.

Formatting number as a currency

To define formatter use Intl.NumberFormat. Here’s an example of formatter for en-US locale and USD currency

const usdFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

usage:

const number = 123.45;

const formattedValue = usdFormatter.format(number);

console.log(formattedValue);
// $123.45

Other examples:

new Intl.NumberFormat('pl-PL', { style: 'currency', currency: 'PLN' }).format(
  number
);
// 123,45 zł

new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(
  number
);
// 123,45 €

Customizing fraction part

To customize fraction part, you can use minimumFractionDigits parameter

new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(
  12345.6789
);
// 12.345,68 €

new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
  minimumFractionDigits: 3,
}).format(12345.6789);
// 12.345,679 €

Using currency code instead of a symbol

To use currency code instead of a symbol, you can use currencyDisplay parameter

new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  currencyDisplay: 'symbol',
}).format(12345.6789);
// $12,345.68

new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  currencyDisplay: 'code',
}).format(12345.6789);
// USD 12,345.68

new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  currencyDisplay: 'name',
}).format(12345.6789);
// 12,345.68 US dollars