Repository Public
1import type { Locale } from "@/schema";23const cache = new Map<string, Intl.NumberFormat>();4function nf(locale: Locale, min: number, max: number): Intl.NumberFormat {5 const key = `${locale}|${min}|${max}`;6 let f = cache.get(key);7 if (!f) { f = new Intl.NumberFormat(locale, { minimumFractionDigits: min, maximumFractionDigits: max }); cache.set(key, f); }8 return f;9}1011/** A number for readers, in the sheet's locale. Non-finite values are shown as a dash. */12export function fmt(locale: Locale, v: number | null | undefined, digits = 2, fixed = false): string {13 if (v === null || v === undefined || !Number.isFinite(v)) return "—";14 const r = Object.is(v, -0) || Math.abs(v) < 0.5 * 10 ** -digits ? 0 : v;15 return nf(locale, fixed ? digits : 0, digits).format(r);16}17export function fmtInt(locale: Locale, v: number): string { return fmt(locale, v, 0); }18export function fmtPct(locale: Locale, v: number, digits = 1): string {19 if (!Number.isFinite(v)) return "—";20 return `${fmt(locale, v * 100, digits)}${locale === "fr" ? " %" : "%"}`;21}22/** Decimals needed to show a value on a grid of the given step. */23export function decimalsOf(step: number): number {24 if (!(step > 0) || step >= 1) return Number.isInteger(step) ? 0 : 2;25 return Math.min(6, Math.max(0, Math.ceil(-Math.log10(step) - 1e-9)));26}27/** SVG coordinate with two decimals (keeps markup short and stable between server and browser). */28export function px(v: number): number { return Math.round(v * 100) / 100; }29