How to Format Numbers in JavaScript using Intl.NumberFormat

ratracegrad

Jennifer Bland

Posted on May 11, 2022

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.
šŸ’– šŸ’Ŗ šŸ™… šŸš©
ratracegrad
Jennifer Bland

Posted on May 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related