DEV Community

Cover image for How to Format Numbers in JavaScript using Intl.NumberFormat
Jennifer Bland
Jennifer Bland

Posted on • Originally published at jenniferbland.com

4 3

How to Format Numbers in JavaScript using Intl.NumberFormat

If you ever wanted to format a number in JavaScript you were forced to use .toLocaleString(). The only challenge was this does not actually support locales. It uses the system locale. Now with the Intl.NumberFormat() to format any number into a currency value and format it based on a locale.

Here is an example of how we use to format numbers using .toLocaleString():

const money = 1000;

money.toLocaleString('en-US', { 
    style: 'currency', currency: 'USD' 
}); // $1,000.00
Enter fullscreen mode Exit fullscreen mode

Now with ES6 JavaScript gives us the Intl object which is the ECMAScript Internationalization API. This API provides language sensitive number formatting.

Here is the same example as above:

new Intl.NumberFormat('en-US', { 
    style: 'currency', currency: 'USD' 
}).format(money); // $1,000/00
Enter fullscreen mode Exit fullscreen mode

Formatting Currency in Different Locales

Here are several examples of formatting money using the Euro and the Japanese Yen:

new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
}).format(money); // '€ 10,000.00'

new Intl.NumberFormat('jp-JP', {
  style: 'currency',
  currency: 'JPY',
}).format(money); // 'JP¥ 10,000'
Enter fullscreen mode Exit fullscreen mode

Syntax for Intl.NumberFormat

Here are the syntax options available:

new Intl.NumberFormat()
new Intl.NumberFormat(locales)
new Intl.NumberFormat(locales, options)
Enter fullscreen mode Exit fullscreen mode

Parameters

  • locales - (optional) A string with a BCP 47 language tag, or an array of such strings. Can provide multiple locales where the best-supported locale will be favored in the order provided by the array. Locales is the language and region setting. It is made up of language code and the country code.
  • options - (optional) Provides settings indicating how a number should be formatted to a string. There are tons of options and you can review them on the documentation page.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay