Locale is specified as a string. Normally
language (2 char, lower case) “-” Country (2 char, upper case)
but can also include a script (latn (Latin), cyrl (Cyrillic), hans (simplified chinese) and variants and extensions.
Numbers
let myNumber = 12345.67
console.log(myNumber.toLocaleString(“en-GB”)); // → 12,345.67
console.log(myNumber.toLocaleString(“de-DE”)); // → 12.345,67
Also number formatter
let formatter = new Intl.NumberFormat(“de”);
formatter.format(12345.67);
You can add options
let formatter = new Intl.NumberFormat(“de”, {style:”currency”, currency:”EUR”});
formatter.format(12345.67); → 12.345,67 €
Options include
- styles: decimal (default), currency, percent
- currency: ISO4217 code
- currencyDisplay: symbol (default), code, name
- minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits,
Dates
let myDate = new Date();
console.log(myDate.toLocaleString(“en”)); //→ 5/17/2022, 8:41:38 PM
console.log(myDate.toLocaleDateString(“en-GB”)); // → 17/05/2022
console.log(myDate.toLocaleTimeString(“en”)); // → 8:41:38 PM
Note “en” defaults to “en-US”.
Also date formatter
let formatter = new Intl.DateTimeFormat(“en”);
formatter.format(myDate);
Can add options
let formatter = new Intl.DateTimeFormat(“en”, {});
formatter.format(myDate);
Options include
- timezone: UTC, Europe/London, Europe/Paris
- dateStyle, timeStyle: full, long, medium, short
- month: 2-digit, numeric, narrow, short, long
- year, day, hour, minute, second: 2-digit, numeric
- weekday, era: short, long, narrow
- timeZoneName: short, long
Other functions include generating text for a “relative time”.
let formatter = new Intl.RelativeTimeFormat(“en”, {});
console.log(formatter.format(3, “hours”); //→ in 3 hours
Sorting & Collation
When sorting an array, there was the comparator function
myArray.sort( (x,y) => x.localeCompare(y) )
Can also use a collator for localised collation.
const swedishCollator = new Intl.Collator(“sv”);
myArray.sort(swedishCollator.compare)