An engineer used a floating-point type to store monetary amounts, and now a totals report is off by a cent in some cases. Walk me through why this happens and what you'd use instead.
technical-conceptual · Senior level · software-engineering
What the interviewer is really asking
Assesses whether the candidate understands how IEEE 754 represents values in binary, why decimal fractions and summation order cause rounding error, and can choose a representation appropriate to money rather than reciting 'don't use floats' without the mechanism.
What to say
- Explain the mechanism: IEEE 754 binary floating point can't represent most decimal fractions like 0.10 exactly, so each value carries a tiny rounding error that accumulates across operations.
- Add that floating-point addition isn't associative, so the order a parallel or batched sum runs in can change the last cent — making results non-reproducible across runs.
- Pick a fit-for-purpose representation: integer minor units (cents) or a decimal type, so money is exact and rounding is an explicit, controlled step rather than an emergent artifact.
What to avoid
- Hand-waving 'floats are imprecise' with no account of binary representation or non-associative summation.
- Proposing to round at the end as the fix, which hides but doesn't eliminate the accumulated error and still drifts on large datasets.
- Reaching for a wider float (double instead of float) and assuming more bits makes the decimal-representation problem go away.
Example answers
Strong: The mechanism is that 0.10 has no exact binary representation in IEEE 754, so every amount carries rounding error, and because float addition isn't associative the batched sum drifted differently than the row-by-row total. I moved money to integer cents end to end, with rounding only at explicit display and tax boundaries. The penny discrepancies disappeared and totals became reproducible regardless of summation order.
Weak: Floats lose precision, so I'd round the total to two decimal places at the end, and switch from float to double for more accuracy in the meantime.