/** * Number formatting helpers used by `` and ``. * * Mirrors `packages/react/src/utils/formatNumber.ts`. A module-scope cache * keyed by `(locale, options)` keeps repeated formats cheap — constructing * `Intl.NumberFormat` dominates the cost. */ const FORMATTER_CACHE = new Map(); export function getFormatter( locale?: Intl.LocalesArgument, options?: Intl.NumberFormatOptions, ): Intl.NumberFormat { const key = JSON.stringify({ locale, options }); const cached = FORMATTER_CACHE.get(key); if (cached) return cached; const formatter = new Intl.NumberFormat(locale, options); FORMATTER_CACHE.set(key, formatter); return formatter; } /** * Formats `value` with `Intl.NumberFormat(locale, format)`. Returns the * empty string when `value` is `null` or non-finite so the visible `` * can clear cleanly. */ export function formatNumber( value: number | null, locale?: Intl.LocalesArgument, format?: Intl.NumberFormatOptions, ): string { if (value == null || Number.isNaN(value)) return ""; return getFormatter(locale, format).format(value); } /** * Like {@link formatNumber} but forces maximum precision (20 fraction * digits) when the caller didn't pin an explicit precision. Used for * controlled-input display where the consumer's `value` prop must round-trip * through the formatter without losing digits. */ export function formatNumberMaxPrecision( value: number | null, locale?: Intl.LocalesArgument, format?: Intl.NumberFormatOptions, ): string { if (value == null || Number.isNaN(value)) return ""; const nextFormat: Intl.NumberFormatOptions = { ...format, maximumFractionDigits: 20, }; return getFormatter(locale, nextFormat).format(value); }