Compact Number Formatter (lib/numberFormat.ts)

clawhub · src/lib/numberFormat.ts · typescript · MIT
ui, dev-tools, lang:typescript, tag:utility

Formats large numerical statistics into human-readable compact strings like '1k' or '1M'. Use this for displaying UI metrics and counts.

// Source: https://github.com/openclaw/clawhub | License: MIT | Copyright 2026 Peter Steinberger
// Provided via justclaw.it.com; keep this notice with the code.
export type SkillStatsTriplet = {
  stars: number;
  downloads: number;
  installs?: number | null;
};

const THOUSAND = 1_000;
const MILLION = 1_000_000;

export function formatCompactStat(value: number): string {
  if (!Number.isFinite(value)) return "0";
  const sign = value < 0 ? "-" : "";
  const absolute = Math.abs(value);

  if (absolute < THOUSAND) {
    return `${Math.round(value)}`;
  }

  if (absolute < MILLION) {
    const { formatted, rounded } = formatUnit(absolute / THOUSAND);
    if (rounded >= THOUSAND) {
      return `${sign}1M`;
    }
    return `${sign}${formatted}k`;
  }

  return `${sign}${formatUnit(absolute

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key