Number formatting
Locale-aware compact numbers ("1.2K"), file sizes, durations and relative times with the built-in Intl APIs — no library.
The browser ships CLDR, the same locale database ICU and every OS use. With
Intl.NumberFormat, Intl.DurationFormat and Intl.RelativeTimeFormat you
get correct output in hundreds of locales for zero bytes of bundle. The one
thing Intl never does is pick the unit for you — choosing between kB
and MB, or minutes and hours, is always your code.
All helpers below live in one file:
Install with the shadcn CLI, or copy the source below.
npx shadcn@latest add https://ui-patterns.stereobooster.com/r/format.jsonexport function formatCompact(
value: number,
locale?: string,
compactDisplay: "short" | "long" = "short",
) {
return new Intl.NumberFormat(locale, {
notation: "compact",
compactDisplay,
}).format(value);
}
const SI_UNITS = [
"byte",
"kilobyte",
"megabyte",
"gigabyte",
"terabyte",
"petabyte",
] as const;
const IEC_UNITS = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"] as const;
export function formatBytesToParts(
bytes: number,
locale?: string,
{ binary = false }: { binary?: boolean } = {},
): Intl.NumberFormatPart[] {
const base = binary ? 1024 : 1000;
const last = SI_UNITS.length - 1;
let i = 0;
let value = bytes;
while (value >= base && i < last) {
value /= base;
i++;
}
// 999_950 B would otherwise render as "1,000 kB" after rounding.
if (i < last && Number(value.toFixed(i === 0 ? 0 : 1)) >= base) {
value /= base;
i++;
}
const maximumFractionDigits = i === 0 ? 0 : 1;
if (binary) {
return [
...new Intl.NumberFormat(locale, { maximumFractionDigits }).formatToParts(
value,
),
{ type: "literal", value: " " },
{ type: "unit", value: IEC_UNITS[i] },
];
}
return new Intl.NumberFormat(locale, {
maximumFractionDigits,
style: "unit",
unit: SI_UNITS[i],
// CLDR's short form for a bare byte is "999 byte" in English.
unitDisplay: i === 0 ? "long" : "short",
}).formatToParts(value);
}
export function formatBytes(
bytes: number,
locale?: string,
options?: { binary?: boolean },
) {
return formatBytesToParts(bytes, locale, options)
.map((p) => p.value)
.join("");
}
export type DurationStyle = "long" | "short" | "narrow" | "digital";
export function splitSeconds(totalSeconds: number) {
const s = Math.max(0, Math.round(totalSeconds));
return {
hours: Math.floor(s / 3600),
minutes: Math.floor((s % 3600) / 60),
seconds: s % 60,
};
}
export function formatDuration(
totalSeconds: number,
locale?: string,
style: DurationStyle = "short",
) {
const duration = splitSeconds(totalSeconds);
if (typeof Intl.DurationFormat === "function") {
return new Intl.DurationFormat(locale, {
style,
// "auto" drops zero seconds: a zero duration becomes "" and
// one hour in digital style becomes "1:00".
secondsDisplay:
style === "digital" || totalSeconds < 0.5 ? "always" : "auto",
}).format(duration);
}
if (style === "digital") {
const pad = (n: number) => String(n).padStart(2, "0");
return `${duration.hours}:${pad(duration.minutes)}:${pad(duration.seconds)}`;
}
const entries = (["hours", "minutes", "seconds"] as const).filter(
(key, _, all) =>
duration[key] > 0 ||
(key === "seconds" && all.every((k) => !duration[k])),
);
return new Intl.ListFormat(locale, { type: "unit", style }).format(
entries.map((key) =>
new Intl.NumberFormat(locale, {
style: "unit",
unit: key.slice(0, -1),
unitDisplay: style,
}).format(duration[key]),
),
);
}
const RELATIVE_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
["year", 365 * 24 * 3600],
["month", 30 * 24 * 3600],
["week", 7 * 24 * 3600],
["day", 24 * 3600],
["hour", 3600],
["minute", 60],
["second", 1],
];
export function formatRelative(
secondsFromNow: number,
locale?: string,
numeric: "auto" | "always" = "auto",
) {
const rtf = new Intl.RelativeTimeFormat(locale, { numeric });
const abs = Math.abs(secondsFromNow);
for (const [unit, size] of RELATIVE_UNITS) {
if (abs >= size || unit === "second") {
return rtf.format(Math.round(secondsFromNow / size), unit);
}
}
return rtf.format(0, "second");
}Compact numbers
"12K followers", "1.5M views". Switch the locale to see why
n / 1000 + "K" is wrong almost everywhere outside English.
Notes:
- Thresholds differ per locale. German doesn't abbreviate thousands at
all (
999.999, then1,5 Mio.). Japanese groups by 10⁴, so 12,345 is1.2万and 1,500,000 is150万. Indian English uses lakh/crore: 1,500,000 is15L. A hand-rolledK/M/Bsuffix is only right for English. - Rounding is to ~2 significant digits. 1,234 →
1.2K, 12,345 →12K. PassmaximumFractionDigits/maximumSignificantDigitsto change it. - 999,999 shows as
1M. Usually fine, but it can look like a lie next to an exact counter elsewhere on the page. - Keep the exact value reachable. The demo puts the full number in
title. For counts people care about (money, votes) show the exact number on the detail view. compactDisplay: "long"gives1.2 thousand/1,2 Millionen— useful for screen readers viaaria-labelwhile the visual text stays short.
File sizes
Intl has byte units but no auto-scaling, so the helper picks the unit and
Intl formats it. The unit is rendered smaller and muted via
formatToParts — splitting the formatted string on a space breaks in
locales that put the unit first or use no space.
Notes:
- 1000 vs 1024 is a product decision. macOS, iOS, Android and disk
manufacturers use SI (÷1000,
kB/MB/GB). Windows divides by 1024 but labels itKB/MB/GB. If you need ÷1024, label it honestly asKiB/MiB/GiB—Intlhas no IEC units, so the helper appends them itself. Pick one and use it everywhere in the product; mismatches between an upload limit and an error message are the classic bug. - Rounding can overflow the unit. 999,950 bytes is 999.95 kB, which
rounds to
1,000 kB. The helper bumps to the next unit after rounding so it shows1 MB. - Bare bytes use the long form. CLDR's short English label for a byte
is
byte(999 byte), so the helper switches tounitDisplay: "long"below 1 kB:999 bytes,999 octets. - French says octets.
1,2 Mo,5 Go— another reason not to hard-code"MB".
Durations
For a length of time — video length, ETA, time spent — use
Intl.DurationFormat. It shipped in all major browsers in 2025; the helper
falls back to Intl.ListFormat + unit formatting on older engines.
Notes:
- No balancing.
format({ seconds: 3905 })prints3,905 sec, not1 hr, 5 min, 5 sec. Split into hours / minutes / seconds yourself (splitSeconds). - Zero units are hidden by default — which also hides the seconds of a
zero-length duration (output: empty string) and drops
:00seconds indigitalstyle (1:00for one hour). The helper forcessecondsDisplay: "always"in those cases. digitalis for media players and timers (1:05:05). Useshortornarrowfor UI chrome where space is tight.
Relative time
For a point in time relative to now — "2 minutes ago", "yesterday", "in
3 days" — use Intl.RelativeTimeFormat. Again you pick the unit.
Notes:
numeric: "auto"turns-1 dayintoyesterdayand, in German,-2 daysintovorgestern. Use"always"when the output sits in a column and needs to be uniform.- Months and years are approximate here (30 / 365 days). For "last month" to be calendar-accurate, compare calendar fields instead of dividing seconds.
- Show the absolute time too. Wrap it in
<time dateTime={iso} title={absolute}>so hover and assistive tech get the exact moment. - It goes stale. "2 minutes ago" is wrong ten minutes later. Re-render on an interval sized to the unit (every second under a minute, every minute under an hour, …).
Tabular figures
Formatting picks the characters; the font decides how wide each digit is.
Most UI fonts default to proportional digits — 1 is much narrower
than 8 (in Inter, 1111 is about a third narrower than 8888). That
looks good in prose, but anything that updates in place shifts sideways on
every tick, and right-aligned columns stop lining up at the decimal point.
font-variant-numeric: tabular-nums (Tailwind: tabular-nums) switches
to the font's equal-width digits.
.timer,
.price,
td.numeric {
font-variant-numeric: tabular-nums;
}Notes:
- Use it for anything that changes or stacks: timers, counters, progress percentages, prices in a list, table columns, slider readouts. The sliders on this page use it — without it their labels wiggle while you drag.
- Keep proportional digits in prose. Tabular
1gets padded to the width of8, so "in 1991" looks gappy in a paragraph. - The font must ship the feature (OpenType
tnum). Inter, Geist, Roboto, SF and IBM Plex do. If it's missing, the property silently does nothing — and the metric-matched fallbacknext/fontshows before the web font loads doesn't have it either. - Monospace fonts don't need it. Every glyph is already the same width; that's why the result rows above don't jitter.
- Alignment still needs
text-align: right(or alignment on the decimal separator). Equal-width digits only line up when the numbers share the same number of decimals — format with a fixedminimumFractionDigitsfor money. - Related features under the same property:
slashed-zero(0vsOin codes and IDs),lining-nums/oldstyle-nums(digits at cap height vs text-style digits with descenders),diagonal-fractions(1/2→ ½),ordinal(1st). Fonts like Inter also have character variants viafont-feature-settings(e.g. a1with a base that can't be confused withl) — check the font's docs for the tags.
Server rendering and hydration
Passing undefined as the locale means "whatever the runtime's default
is". The server and the browser rarely agree, and relative times also
depend on when they're rendered, so both cause React hydration
mismatches.
- Pass an explicit locale everywhere — from the user's settings, the
URL, or
Accept-Languageon the server. The demos above all start from an explicit"en-US"for this reason. - For anything computed from
Date.now(), render a stable value on the server (the absolute date) and swap in the relative string after mount, or addsuppressHydrationWarningon the<time>element. - Cache formatter instances in hot paths. Constructing an
Intl.NumberFormatis far more expensive than calling.format(); in a long table, create one per locale + options and reuse it.