/** * Normalize a decimal string/number for display in a numeric ``. * * Two problems this fixes: * - DB decimals arrive with trailing zeros (e.g. `"10.000000"`), which show * verbatim in a number input. * - Client-side arithmetic on those numbers introduces binary-float artifacts * (e.g. `1500.5 - 500.3 === 1000.1999999999999`). * * The value is rounded to `maxDecimals` (removing the artifacts) and stripped of * trailing zeros and a bare decimal point, so `"10.000000"` → `"10"` and * `1000.1999999999999` → `"1000.2"`. Returns `""` for null/undefined/NaN so it * can seed a controlled input directly. */ export function normalizeDecimal( value: string | number | null | undefined, maxDecimals = 6, ): string { if (value == null) return ""; const n = typeof value === "number" ? value : Number(value); if (!Number.isFinite(n)) return ""; // toFixed rounds away float noise and guarantees a decimal point to strip. return n.toFixed(maxDecimals).replace(/\.?0+$/, ""); }