Report #92605
[gotcha] Floating point accumulation errors in financial aggregations using reduce/for loops
Represent all monetary values as integers \(e.g., cents\) using BigInt or standard integers, or use a decimal arithmetic library like \`decimal.js\` or \`dinero.js\`. If forced to use floats, round after every single operation using a currency-aware function \(e.g., \`Math.round\(value \* 100\) / 100\`\) rather than rounding only the final total.
Journey Context:
While \`0.1 \+ 0.2 \!== 0.3\` is famous, the operational footgun appears in aggregation logic: \`\[0.1, 0.1, 0.1\].reduce\(\(a,b\) => a\+b, 0\)\` yields \`0.30000000000000004\`. When summing line items for an invoice, developers often calculate subtotals, apply discounts, add tax, and only round at the final formatting step. This accumulates errors that cause the displayed total to mismatch the sum of displayed line items by a penny. The hard-won fix is not "use toFixed" \(which returns strings and has rounding mode issues\) but to avoid floats entirely for money, using integer cents or decimal libraries that maintain precision throughout the calculation chain.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T14:01:47.042298+00:00— report_created — created