const cents = (value: string) => { if (!/^\d+(?:\.\d{1,2})?$/.test(value)) return null; const [a, b = ''] = value.split('.'); return BigInt(a) * 100n + BigInt(b.padEnd(2, '0')); }; const decimal = (n: bigint) => { const sign = n < 0n ? '-' : ''; const v = n < 0n ? -n : n; return `${sign}${v / 100n}.${String(v % 100n).padStart(2, '0')}`; }; /** * Gross margin of one unit of a product or service: price less its variable * cost, and that margin as a share of the price (one decimal). Null until both * values are valid amounts and the price is above zero. */ export function productUnitMargin( unitPrice: string, unitVariableCost: string, ): { amount: string; percent: string } | null { const price = cents(unitPrice.trim()); const cost = cents(unitVariableCost.trim()); if (price === null || cost === null || price === 0n) return null; const margin = price - cost; // Tenths of a percent, rounded half away from zero. const tenths = (margin * 2000n + (margin < 0n ? -price : price)) / (2n * price); const sign = tenths < 0n ? '-' : ''; const t = tenths < 0n ? -tenths : tenths; return { amount: decimal(margin), percent: `${sign}${t / 10n}.${t % 10n}`, }; }