DEV Community

Amit Mondal
Amit Mondal

Posted on

JavaScript Internationalization

Intl is a powerful object that exposes the JavaScript Internationalization API.
The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. I won't be mentioning all but a few which caught my attention and can be handy.

1) Convert digits into currency:

new Intl.NumberFormat('en-IN', {
  style: 'currency',
  currency: 'INR',
  minimumFractionDigits: 0
}).format(1150000); // "₹11,50,000"

new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 0
}).format(1150000); // "$1,150,000"

new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'JPY',
  minimumFractionDigits: 0
}).format(1150000); // "ï¿¥1,150,000"
Enter fullscreen mode Exit fullscreen mode

2) Convert Digits to Compact(rounding with notation):

new Intl.NumberFormat(undefined, {
  notation: 'compact'
}).format(1150000); // "1.2M"

new Intl.NumberFormat(undefined, {
  notation: 'compact'
}).format(11500); // "12K"
Enter fullscreen mode Exit fullscreen mode

3) Format Date to mentioned locale prefers:

const date = new Date();
dateTimeFormatter = new Intl.DateTimeFormat('en-IN');
dateTimeFormatter.format(date); // "29/8/2020"

dateTimeFormatter = new Intl.DateTimeFormat('en-US')
dateTimeFormatter.format(date) // "8/29/2020"

/*The formatToParts() method returns an array with all the date parts:*/
const date = new Date()
const dateTimeFormatter = new Intl.DateTimeFormat('en-IN')
dateTimeFormatter.formatToParts(date)
/*
[
  {
    "type": "day",
    "value": "29"
  },
  {
    "type": "literal",
    "value": "/"
  },
  {
    "type": "month",
    "value": "8"
  },
  {
    "type": "literal",
    "value": "/"
  },
  {
    "type": "year",
    "value": "2020"
  }
]
*/
Enter fullscreen mode Exit fullscreen mode

4) Plural Rules Formatting tells you which form applies based on a given number for a specific locale:

const pr = new Intl.PluralRules('en-US', {
    type: 'ordinal'
})
pr.select(0) //other
pr.select(1) //one
pr.select(2) //two
pr.select(3) //few
pr.select(4) //other
pr.select(10) //other
pr.select(22) //two

// Every time we get other, we translate that to th. If we have one, we use st. For two we use nd. few gets rd.
const suffixes = {
  'one': 'st',
  'two': 'nd',
  'few': 'rd',
  'other': 'th'
}

const format = (number) => `${number}${suffixes[pr.select(number)]}`

format(0) //0th
format(1) //1st
format(2) //2nd
format(3) //3rd
format(4) //4th
format(21) //21st
format(22) //22nd
Enter fullscreen mode Exit fullscreen mode

Top comments (0)