Rounding Errors in Financial Calculations
You'll learn why floating-point math creates problems when working with money, and how to avoid costly mistakes.
The Problem with Money
When you calculate prices, taxes, or account balances using JavaScript's Number type, tiny rounding errors can accumulate into significant mistakes. Remember that 0.1 + 0.2 !== 0.3? Now imagine performing hundreds or thousands of calculations on currency values—those errors compound.
let balance = 0.1;
balance += 0.2;
console.log(balance); // 0.30000000000000004
// In a loop, errors multiply:
let total = 0;
for (let i = 0; i < 10; i++) {
total += 0.1;
}
console.log(total); // 0.9999999999999999 (not 1!)
Common Mitigation Strategies
1. Work in cents (integers): Store monetary values as integers representing the smallest currency unit. Instead of $10.50, store 1050 cents. Integer arithmetic is exact in the safe integer range.
let priceInCents = 1050; // $10.50
let taxInCents = 105; // $1.05
let totalInCents = priceInCents + taxInCents; // 1155 (exact!)
let totalDollars = totalInCents / 100; // Convert back: $11.55
2. Round at display time: Perform calculations with full precision, but use toFixed() only when showing results to users, never during intermediate steps.
let calculation = 0.1 + 0.2;
console.log(calculation.toFixed(2)); // "0.30"
Key Takeaway: Floating-point errors are disastrous for financial calculations. Always store money as integers (cents) when possible, or round only at the final display step—never during intermediate arithmetic.