Compact Number Formatting

Format large counts as 1.2K or 3.4M with Intl.NumberFormat compact notation and configurable locale and precision.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
export function formatCompactNumber(value, locale = "en", options = {}) {
  if (typeof value !== "number" || !Number.isFinite(value)) {
    throw new TypeError("value must be a finite number");
  }
  const { maximumFractionDigits = 1, ...rest } = options;
  if (!Number.isInteger(maximumFractionDigits) || maximumFractionDigits < 0) {
    throw new RangeError("maximumFractionDigits must be a non-negative integer");
  }
  return new Intl.NumberFormat(locale, {
    notation: "compact",
    compactDisplay: "short",
    maximumFractionDigits,
    ...rest,
  }).format(value);
}

export function formatCompactRange(values, locale = "en") {
  if (!Array.isArray(values)) throw new TypeError("values must be an array");
  return values.map((value) => formatCompactNumber(value, locale)).join(" – ");
}

How it works

Count the functions formatCompactNumber and formatCompactRange as the entire surface area of Compact Number Formatting.

The code refuses to proceed on bad state and throws TypeError and RangeError at its guard.

The return value is newly constructed — inputs are never handed back.

Applying it

The primary signature is export function formatCompactNumber(value, locale = "en", options = {})

formatCompactNumber is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

return values.map((value) => formatCompactNumber(value, locale)).join(" – ");
return new Intl.NumberFormat(locale, {
notation: "compact",
compactDisplay: "short",
maximumFractionDigits,
...rest,
}).format(value);
throw new RangeError("maximumFractionDigits must be a non-negative integer");

Interactive Tools for This Topic

FAQ

Does `formatCompactNumber` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
What does the snippet do with malformed data?
The code throws `TypeError` and `RangeError`. Handle it at the call site or let it propagate deliberately.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `formatCompactNumber`, `formatCompactRange` at load time.