🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

The Intl API: Locale-Aware Formatting in the Browser

Web FoundationsInternationalization🟢 Free Lesson

Formatting for Every Locale with Intl

Numbers and dates look simple until they cross a border. A price of 1234.5 reads as twelve hundred and thirty-four point five in one country and as one million two hundred thousand in another, because the thousands separator and the decimal mark trade places. Dates are worse: 03/04/2026 is March in one region and April in another, and no amount of string concatenation will guess right. The Intl API moves all of that judgement into the browser, where the rules ship with the engine and are updated with it.

Five constructors cover the overwhelming majority of needs. Intl.NumberFormat handles numeric and currency display, Intl.DateTimeFormat handles calendar dates, Intl.RelativeTimeFormat handles "three days ago", Intl.PluralRules decides which plural form a count needs, and Intl.Collator compares strings the way a human would sort them. Intl.ListFormat and Intl.DisplayNames round out the set for enumerated text and localized names of languages, regions, and currencies.

A few principles apply across all of them:

  • formatting is a lookup, not arithmetic, so build the formatter once and reuse it
  • the locale argument accepts a full BCP 47 tag, a partial tag, or an array for fallback order
  • the same data must be formatted for the user's locale, not the server's
  • none of these objects perform translation; they only arrange and inflect what you give them

Choosing the Locale You Format For

Before any formatter runs, one decision determines everything: which locale tag to pass. The browser offers navigator.language, but that value reflects the interface language of the browser, not necessarily the reader's number conventions or the language they chose inside your app. A user running an English interface in Berlin wants comma decimal points and German date order, and the two preferences can differ.

The robust approach stores an explicit locale with the user's profile, falls back to the most specific entry of the Accept-Language request header, and only then to the browser default. Passing an array of candidates lets the engine walk the list until it finds one it supports:

javascript
function pickLocale(preferred = [], available = ['en-GB', 'en']) {
  for (const candidate of preferred) {
    const exact = available.find(
      (tag) => tag.toLowerCase() === candidate.toLowerCase()
    );
    if (exact) return exact;
    const base = available.find(
      (tag) => tag.split('-')[0] === candidate.split('-')[0]
    );
    if (base) return base;
  }
  return available[0];
}

const header = 'de-DE,de;q=0.9,en;q=0.8';
const requested = header
  .split(',')
  .map((part) => {
    const [tag, q = 'q=1'] = part.trim().split(';');
    return { tag, weight: Number(q.replace('q=', '')) };
  })
  .sort((a, b) => b.weight - a.weight)
  .map((entry) => entry.tag);

console.log(pickLocale(requested));   // de-DE when the app offers it

Unicode extension subtags are worth knowing too. The tag ar-EG-u-nu-latn requests Arabic locale rules with Latin numerals, which many products prefer for legibility. The same extension works on every Intl constructor, so a single stored preference can steer numerals, calendars, and week numbering together.

NumberFormat for Money and Percentages

The style option changes which parts of the output the API controls. With decimal, you get separators. With currency, you get the symbol, its position, and the correct number of fraction digits for that currency, all of which vary: the yen has none, the dollar has two, and the dinar has three. With percent, the value is multiplied by one hundred as it renders, so passing 0.086 displays 8.6 per cent rather than 0.086.

javascript
const locale = navigator.language;
const money = new Intl.NumberFormat(locale, {
  style: 'currency',
  currency: 'EUR'
});
const percent = new Intl.NumberFormat(locale, {
  style: 'percent',
  minimumFractionDigits: 1,
  maximumFractionDigits: 1
});
const compact = new Intl.NumberFormat(locale, {
  notation: 'compact',
  maximumSignificantDigits: 3
});

const samples = {
  subtotal: 1234.5,
  taxRate: 0.19,
  visitors: 4820000
};

document.getElementById('receipt').textContent =
  `${money.format(samples.subtotal)} + ${percent.format(samples.taxRate)} tax`;

document.getElementById('reach').textContent =
  compact.format(samples.visitors);   // 4.8M or 4,8 M depending on locale

The formatToParts method is the escape hatch when a design needs control over individual glyphs. It returns an array of objects naming each piece, such as currency, integer, group, decimal, and fraction, so you can wrap the currency symbol in a span without parsing the formatted string with a regular expression.

OptionControlsExample of why it exists
styledecimal, currency, percent, unitCurrency symbol placement differs per locale
notationstandard, compact, scientific, engineeringDashboards need 12.3K, tables need 12,300
unitkilometer, celsius, percent and many moreAvoids writing unit text by hand in templates
signDisplayauto, always, exceptZero, negativeFinancial deltas always want an explicit plus
useGroupingThousands separators on or offAccount numbers must not be grouped

💡Currency is not a locale

Deriving the currency symbol from the browser language produces the wrong result for an expatriate or a traveller. Store an explicit ISO currency code with the data and pass it separately from the display locale.

Dates, Times, and Relative Time

Intl.DateTimeFormat accepts either a Date object or an options bag of numeric parts, which is how you avoid the classic time-zone bug: formatting a timestamp with the local zone while the data was recorded in UTC, then watching the date roll back a day. Supply an explicit timeZone whenever the value has one, and let the API do the conversion.

javascript
const stamp = new Date('2026-03-04T22:15:00Z');
const opts = { timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric' };

const long = new Intl.DateTimeFormat(navigator.language, opts);
const short = new Intl.DateTimeFormat(navigator.language, {
  dateStyle: 'medium',
  timeStyle: 'short',
  timeZone: 'UTC'
});
const since = new Intl.RelativeTimeFormat(navigator.language, { numeric: 'auto' });

function relativeTo(date, now = new Date()) {
  const seconds = (date.getTime() - now.getTime()) / 1000;
  const units = [
    ['year', 31536000], ['month', 2592000], ['day', 86400],
    ['hour', 3600], ['minute', 60], ['second', 1]
  ];
  const [, span] = units.find(([, s]) => Math.abs(seconds) >= s) || ['second', 1];
  return since.format(Math.round(seconds / span), span.replace(/s$/, ''));
}

long.format(stamp);                 // 4 March 2026 in most locales
short.format(stamp);                // Mar 4, 2026, 10:15 PM
relativeTo(new Date(Date.now() - 3 * 86400000));  // 3 days ago

Relative time is where the API pays for itself. The numeric: 'auto' option turns "1 day ago" into "yesterday" in locales that have a word for it, and the plural handling of the unit is applied for you, which is exactly the kind of detail that is easy to get wrong in six languages and impossible to notice in one.

Plural Rules and List Formatting

English has two plural forms and a count of zero takes the plural. Many languages have six, and several distinguish a special form for fractions or for counts ending in particular digits. Intl.PluralRules returns the category the locale expects, which you then map onto your own strings; it never translates the string itself.

CategoryTypical use in EnglishTypical use in PolishReturned for
zeroNot usedForm for counts of 0Some locales only
one1 fileSingularCounts equal to 1
twoNot usedForm for 2 and endings in 2A few locales
fewNot used2 to 4, with exceptionsSlavic and other groups
manyNot usedFractional and large valuesSlavic and other groups
otherEverything elseFallbackAlways present
javascript
const rules = new Intl.PluralRules('en');
const forms = {
  one: '{n} file remaining',
  other: '{n} files remaining'
};

function fileMessage(count) {
  return forms[rules.select(count)].replace('{n}', count);
}

const list = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
const disjunction = new Intl.ListFormat('en', { style: 'short', type: 'disjunction' });

list.format(['apples', 'bananas', 'oranges']);        // apples, bananas, and oranges
disjunction.format(['red', 'blue']);                  // red or blue

console.log([1, 0, 2, 5].map(fileMessage).join(' | '));

For a product that ships in more than one language, move the templates into your translation files keyed by plural category. The plural rules then decide which template to load, and translators control the wording without touching code.

Collator: Sorting Names Like a Human

Sorting an array of strings with the default comparison gives code-point order, which places every uppercase letter before every lowercase one and ignores accents entirely. Sorting a list of people or places that way produces results that look broken to a native reader even though they are technically correct.

javascript
const byName = new Intl.Collator(undefined, {
  sensitivity: 'base',
  numeric: true
});

const people = ['Åsa', 'Zoë', 'adam', 'Émile', 'Zoe10', 'Zoe2'];
people.sort(byName.compare);
// adam, Åsa, Émile, Zoe2, Zoe10, Zoë

const files = ['file10.txt', 'file2.txt', 'file1.txt'];
files.sort(new Intl.Collator(undefined, { numeric: true }).compare);
// file1.txt, file2.txt, file10.txt

numeric: true makes embedded digits compare as numbers, which fixes file lists and episode titles in one line. sensitivity: 'base' treats accent-only differences as ties, so searching for "resume" also finds "résumé". Build the collator once per configuration: constructing it repeatedly re-reads locale data and shows up immediately in a profile of a long list.

Caching, Cost, and What Intl Leaves to You

Every formatter is expensive to construct and cheap to call, so the performance rule is to hoist them out of loops and out of render functions. In a component framework that re-renders on each keystroke, a formatter created inside the render body is a formatter created thousands of times. Module scope or a memoized factory removes the cost entirely.

What Intl deliberately does not do is translate. It will format "March" for a French locale only in the sense that it produces the French word for the month if you asked for month names, but it will never turn your product copy into French. It also does not handle fiscal calendars, religious calendars, or user-preferred week start beyond what the locale data provides. And it cannot fix a data model that stores dates as ambiguous strings; that has to be fixed at the point of storage.

Common Mistakes

Constructing a formatter inside a loop or a render function

Fix: Create it once at module scope and reuse it; construction reads locale data and dominates the cost.

Formatting a timestamp without an explicit time zone

Fix: Pass the zone that the data was recorded in, or convert to UTC first, so the displayed date does not depend on the viewer's position.

Deriving the currency from the browser language

Fix: Store an ISO currency code with the value and pass it independently of the display locale.

Sorting with the default string comparison

Fix: Use Intl.Collator with numeric enabled so file names and accented names land in the order users expect.

Key Takeaways

  • Intl moves locale rules into the engine, so separators, symbols, and plural forms stay current without code changes.
  • Build formatters once and cache them; construction is expensive and calls are cheap.
  • Always specify a time zone when formatting stored timestamps.
  • PluralRules selects a category, not a translation, so pair it with templates your translators own.
  • Collator with numeric enabled produces the sort order people expect from file lists and directories.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement