Rounding bugs in payment code are rarely loud. They show up as a one-cent gap in a monthly report, or a refund that is slightly too large.
Why floats fail
Binary floating point cannot store values like 0.1 exactly, so adding amounts can drift. Use integers for stored amounts.
var_dump(0.1 + 0.2 === 0.3); // bool(false)The rules we follow
- Store amounts as integers in minor units, with a currency code in the same row.
- Know your currencies: some, such as the Chilean peso, have no minor unit, so 1,000 means 1,000 pesos, not 10.00.
- Do percentage and tax maths in one place, with a clear rounding rule, and test it.
- Send the provider the amount format it expects. Many APIs take the smallest unit, others take decimals.
- Convert to a display string only at the edge, in the view or API response.
Splitting amounts
When you split a payout or invoice, the parts must add back to the total. Give the leftover cent to a defined recipient instead of rounding each part independently.
Tests worth writing
- Totals with many line items.
- Refunds that equal the original amount.
- Zero-decimal and two-decimal currencies side by side.
