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(" – ");
}Report a problem with this exampleOpens a pre-filled issue on GitHub.