Compact Number Formatting
Format large counts as 1.2K or 3.4M with Intl.NumberFormat compact notation and configurable locale and precision.
Code
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
Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.