Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Formatting with Intl

Different countries write the same number and date differently: 1,234.5 in the USA and 1.234,5 in Germany, 3/8/2026 and 08.03.2026. The built-in Intl object (short for "internationalization") knows these rules and formats values the way the reader is used to.

Numbers

The toLocaleString() method turns a number into a string following the rules of the given language. The language is set with a locale code: 'en-US' is English in the USA, 'de-DE' is German in Germany:

console.log((1234567.891).toLocaleString('en-US')); // 1,234,567.891

Thousands are separated by commas and the fractional part by a dot — as is usual in American English.

Money

Intl.NumberFormat creates a formatter with settings. The currency style adds a currency sign and two decimal places:

const dollars = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
 
console.log(dollars.format(1234.5)); // $1,234.50
console.log(dollars.format(7));      // $7.00

One formatter can be reused for many numbers. A currency code is three letters: USD, EUR.

Percentages and rounding

The percent style multiplies the number by 100 and adds a percent sign, and maximumFractionDigits limits the number of decimal places:

console.log((0.25).toLocaleString('en-US', { style: 'percent' }));            // 25%
console.log((3.14159).toLocaleString('en-US', { maximumFractionDigits: 1 })); // 3.1

Dates

The date method toLocaleDateString() prints a date in a familiar form. Settings let you spell out the month, add the weekday and so on:

const date = new Date(2026, 2, 8);
 
console.log(date.toLocaleDateString('en-US')); // 3/8/2026
console.log(date.toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric' })); // March 8, 2026
console.log(date.toLocaleDateString('en-US', { weekday: 'long' })); // Sunday

For time there is toLocaleTimeString(), and Intl.DateTimeFormat works like NumberFormat: set it up once and format many dates.

Plural words

A word changes with the number: 1 item, 5 items. Intl.PluralRules tells which form is needed. For English it returns one or other; for languages with more forms, such as Russian or Polish, it returns more categories:

const rules = new Intl.PluralRules('en-US');
const forms = { one: 'item', other: 'items' };
 
for (const count of [1, 3, 21]) {
  console.log(`${count} ${forms[rules.select(count)]}`);
}
// 1 item
// 3 items
// 21 items

Common mistake

A formatted string is only meant to be shown to a person. You cannot calculate with it or reliably parse it back: the separators depend on the language.

const price = (1234.5).toLocaleString('en-US');
 
console.log(Number(price)); // NaN

Store and calculate with plain numbers and dates, and format at the very end — right before displaying.

Thanks for reading!

Donate to the site — we work hard for you.