Multiply then divide with widening
amount * rate / divisor is exact only if you multiply first and widen the intermediate. Dividing first truncates to zero; a narrow type overflows. Get the order and the width right or the arithmetic is quietly wrong.
Procedure
- Rewrite every expression to multiply before dividing:
(amount * rate) / divisor, never(amount / divisor) * rate. - Treat
amount * rateas the dangerous product — up to10**exptimes larger than either operand. Check it fits before computing. - Use a widening multiply: Solidity
Math.mulDiv(amount, rate, divisor)forms a 512-bit product then divides to 256-bit; in C use__int128; in Gobig.Int; in Python plainintis arbitrary precision. - Choose the division rounding in the same call:
mulDiv(a, b, d, Rounding.Floor). - When the divisor is a power of ten, confirm the product keeps full precision —
mulDivdoes; a floata * b * 1e-6does not. - If a multiply and a divide by the same factor appear (
a * r / r), cancel only if neither step rounds; a truncated integer round-trip is lossy. - For chained conversions keep the full-precision product through the chain and round once at the end, not per step.
- Test with operands at the type boundary (int64 max, near uint256 max) to surface the overflow that normal-sized inputs hide.
- Prefer a library
mulDivover a hand-rolleda*b/dso the widening and rounding are battle-tested. - Assert the divisor is non-zero before dividing; a zero rate denominator is a config bug that must fail loudly.
- For a rate applied over time, accumulate in the widest unit and divide only at the accrual boundary.
- Keep the intermediate product in the log so a disputed result can be recomputed exactly.
Pitfalls
- Divide-first on small amounts truncates to zero:
(1 / 10_000) * 290 = 0in integers, wiping out the fee. - Storing a wide product back into a narrow variable:
uint128 p = a * boverflows before the division can shrink it. - A float product
amount * 1e-9is inexact for money well below 2^53; use the integer denominator. - Assuming
a * b / d == a * (b / d)for truncated integers — false wheneverb % d != 0. - Forgetting that
mulDivdefaults to Floor rounding, so every ceil case under-charges. - A C
int(32-bit) product of two large money values overflows with UB before you can widen; declare the intermediate as__int128orint64.
Verification
python3 -c "a=7; d=2; b=5; print('divide-first', (a//d)*b, 'multiply-first', (a*b)//d)" # divide-first 15, multiply-first 17
forge test --match-test .*[Mm]ul[Dd]iv -vv
Pass when the wide-order result equals the exact rational rounded once. Report the operands, the order used and the widening type.