Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.5 — Formatting Numbers and Dates
JavaScript · Example 3 of 3

Relative times, lists, plurals and sorting

The default sort compares UTF-16 code units, so capitals come first and item10 before item2. The collator sorts like a person would. 0 from localeCompare means "equal" at base sensitivity (accents ignored).

The built-in Intl object formats numbers, money, percentages, units, dates and times the way each language and country expects: Intl.NumberFormat, Intl.DateTimeFormat and the toLocaleString shortcuts, plus helpers for relative times, lists, plurals and sorting.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write formatINR(paise) that takes whole paise and returns rupees formatted for India, so formatINR(123456789) returns ₹12,34,567.89.

02

Write fileSize(bytes) that shows 512 B, 1.5 kB or 2.3 MB with Intl.NumberFormat and its unit style (use 1000 per step and one decimal).

03

Write timeAgo(minutes) that returns text like 5 minutes ago or 2 hours ago with Intl.RelativeTimeFormat, switching to hours from 60 minutes.

Explain it without notes

01

Why should formatting happen only at display time?

02

What does a locale like en-IN control in Intl.NumberFormat?

03

Why can two computers show different results for date.toLocaleString(), and how do you make them match?

04

When would you use Intl.Collator instead of the default sort?

Relative times, lists, plurals and sorting

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

yesterday | tomorrow | 3 weeks ago
1 day ago
tea, coffee, and juice
tea or coffee
0 items | 1 item | 2 items
[ 'Item1', 'item10', 'item2' ]
[ 'Item1', 'item2', 'item10' ]
0