summaryrefslogtreecommitdiff
path: root/frontend/lib/format.ts
blob: 34bffd83b4e7592a93f84be073df6b1e8d3a5ec8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
export function fmtCurrency(value?: number | null, decimals = 2): string {
  if (value === null || value === undefined || Number.isNaN(value)) return "-";
  return `$${value.toLocaleString(undefined, { maximumFractionDigits: decimals, minimumFractionDigits: decimals })}`;
}

export function fmtNumber(value?: number | null, decimals = 2): string {
  if (value === null || value === undefined || Number.isNaN(value)) return "-";
  return value.toLocaleString(undefined, { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
}

export function fmtLarge(value?: number | null): string {
  if (value === null || value === undefined || Number.isNaN(value)) return "-";
  const abs = Math.abs(value);
  const sign = value < 0 ? "-" : "";
  if (abs >= 1e12) return `${sign}$${(abs / 1e12).toFixed(2)}T`;
  if (abs >= 1e9) return `${sign}$${(abs / 1e9).toFixed(2)}B`;
  if (abs >= 1e6) return `${sign}$${(abs / 1e6).toFixed(1)}M`;
  return `${sign}$${abs.toLocaleString(undefined, { maximumFractionDigits: 0 })}`;
}

export function fmtPct(value?: number | null, decimals = 2, signed = false): string {
  if (value === null || value === undefined || Number.isNaN(value)) return "-";
  const pct = value * 100;
  const sign = signed && pct > 0 ? "+" : "";
  return `${sign}${pct.toFixed(decimals)}%`;
}

export function deltaClass(value?: number | null): string {
  if (value === null || value === undefined) return "neutral";
  return value >= 0 ? "positive" : "negative";
}