Formatting Money in JavaScript with Intl.NumberFormat

JavaScript's Intl.NumberFormat object offers a simple way to format currency values according to different international standards. Here's how:

How to

The Intl.NumberFormat function allows you to format numbers as currency with just a few lines of code.

You specify the user's locale and the currency code, and it handles the rest, including the currency symbol, number formatting, and decimal places.

I think seeing it in action will make it easy.

As an example, to format a number as US dollars:

console.log(
  new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
  }).format(1234.56),
); // Outputs: "$1,234.56"

// Or if you want to make it reusable:
const usFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

console.log(usFormatter.format(1234.56)); // Outputs: "$1,234.56"

In this example, en-US is the locale for the United States, and USD is the currency code for US dollars. The output is "$1,234.56", formatted according to US standards.

Euros Example

For Euros, which are used in many European countries, the formatting changes, and even as a European, I have no idea what to expect. But here's how you would format a value for a specific country easily:

// Germany 
const germanyFormatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
});

console.log(germanyFormatter.format(1234.56)); // Outputs: "1.234,56 €"

Notice how the comma and period roles are reversed, which is standard in many European countries, and the currency symbol is placed after the number.

Customizing the Format

There is a lot more options, and I think the best exhaustive list I could find for you to read through is here.

But as an example you can alter the options to do a lot of cool thing that might otherwise require a hacky solution.

For example, imagine we didn't care about cents.

You can adjust the number of decimal places shown with maximumFractionDigits to 0, and it just works.

Here's an example:

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

console.log(usFormatterNoCents.format(1234)); // Outputs: "$1,234"

I hope this short introduction shows you how useful the Intl.NumberFormat object is. 🚀

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.