UI Patterns
Display

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.json
lib/format.ts
export 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.

compact short1.2K
compact long1.2 thousand
naive n / 1000 + 'K'1.2K

Notes:

  • Thresholds differ per locale. German doesn't abbreviate thousands at all (999.999, then 1,5 Mio.). Japanese groups by 10⁴, so 12,345 is 1.2万 and 1,500,000 is 150万. Indian English uses lakh/crore: 1,500,000 is 15L. A hand-rolled K/M/B suffix is only right for English.
  • Rounding is to ~2 significant digits. 1,234 → 1.2K, 12,345 → 12K. Pass maximumFractionDigits / maximumSignificantDigits to 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" gives 1.2 thousand / 1,2 Millionen — useful for screen readers via aria-label while 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.

SI (÷1000) — macOS, iOS, Android1.2 MB
IEC (÷1024)1.2 MiB

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 it KB/MB/GB. If you need ÷1024, label it honestly as KiB/MiB/GiB — Intl has 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 shows 1 MB.
  • Bare bytes use the long form. CLDR's short English label for a byte is byte (999 byte), so the helper switches to unitDisplay: "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.

long1 hour, 5 minutes, 5 seconds
short1 hr, 5 min, 5 sec
narrow1h 5m 5s
digital1:05:05

Notes:

  • No balancing. format({ seconds: 3905 }) prints 3,905 sec, not 1 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 :00 seconds in digital style (1:00 for one hour). The helper forces secondsDisplay: "always" in those cases.
  • digital is for media players and timers (1:05:05). Use short or narrow for 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.

numeric: "auto"yesterday
numeric: "always"1 day ago

Notes:

  • numeric: "auto" turns -1 day into yesterday and, in German, -2 days into vorgestern. 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.

proportional-nums00:00.00
tabular-nums00:00.00
$1,111.11
$8,888.88
$42.10
$19.99
$7,070.70
.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 1 gets padded to the width of 8, 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 fallback next/font shows 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 fixed minimumFractionDigits for money.
  • Related features under the same property: slashed-zero (0 vs O in 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 via font-feature-settings (e.g. a 1 with a base that can't be confused with l) — 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-Language on 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 add suppressHydrationWarning on the <time> element.
  • Cache formatter instances in hot paths. Constructing an Intl.NumberFormat is far more expensive than calling .format(); in a long table, create one per locale + options and reuse it.

On this page