Formatting Number & Date with Intl Object

The Intl object provides access to several constructors, each of them allows to do string comparison, number formatting and date and time formatting.

Two common constructor that Intl provides are,

  • Intl.NumberFormat – Formats a number like decimal, currency based on a locale.
  • Intl.DateFormat – Formats a date based on a locale.

Intl.NumberFormat

const value = 12345

const res = new Intl.NumberFormat('en-GB', { style: 'decimal' }).format(value) // 12,345

const japanese_currency = new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(value) // ¥12,345

In this example,

new Intl.NumberFormat() is a constructor function.

en-GB is a locale. Get locals https://stackoverflow.com/questions/3191664/list-of-all-locales-and-their-short-codes.

style object where we define the formatting style to use. Default is decimal. If you set the value of style “currency” you need to add a currency property and set value ISO 4217 currency code, “USD” for the US dollar, “EUR” for the euro. You can get the full ISO 4217 currency code list here https://www.currency-iso.org/en/home/tables/table-a1.html.

format() takes the formatting value.

Intl.NumberFormat also supports ‘compact’ notation.

const one_million = 1000000
const five_hundred_million = 500000000

new Intl.NumberFormat('en-US', { notation: 'compact' }).format(one_million)// 1M

new Intl.NumberFormat('en-US', { notation: 'compact' }).format(five_hundred_million)// 500M

Intl.DateTimeFormat

Just like number format we can format the date also. For that we have new Intl.DateTimeFormat().

let today = new Date()
// returns the date of today

let us = new Intl.DateTimeFormat('en-US').format(today)// "11/18/2019"; US uses month-day-year order

let gb = new Intl.DateTimeFormat('en-GB').format(today)// "18/11/2019"; British uses day-month-year orde

Additionally we can format the Time also.

new Intl.DateTimeFormat('default', {
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric'
}).format(date)// 7:56:11 PM

Intl.RelativeTimeFormat

const rtf = new Intl.RelativeTimeFormat('en')

rtf.format(5, 'seconds')// "in 5 seconds"

rtf.format(-10, 'seconds')// "10 seconds ago"

4 thoughts on “Formatting Number & Date with Intl Object”

Leave a Comment

Your email address will not be published. Required fields are marked *