Case V · Money without floats
The Ledger of Sand
A cash-flow model is thousands of small sums. Each is off by less than a grain. Together they are a dune.
I · Departure
Thirty years of small numbers
Investmentor is an Australian property investment company. I built the product that guides investors towards their goals, and inside it a cash-flow engine that models tax and depreciation for an investor's portfolio.
Such a model adds rent, interest, tax and depreciation, period after period, for many years. A person will then compare the last line with their own spreadsheet.
II · Initiation
Two ways to lose a cent
The first is the number type. A binary float cannot hold 0.1 exactly, so sums that are equal on paper are not equal in code. Any check written as a + b == total will fail some day.
The second is rounding. Split an amount into three and round each share, and the shares no longer add up to the amount. One cent is nothing. One cent on every invoice is an audit finding.
The cure is the same for both: keep money as whole cents, and decide in code who gets the remainder.
Sandbox · Money without floats
A model, not production data
Press the steps from 1 to 3, then move the invoice total by one cent at a time.
III · Return
What it cost
Integer cents make every division a decision: where does the remainder go? That is more code, and more talks with the people who own the rules. Those talks are the real work.
Patterns in this case
What to call these things
- Money Domain modelling
- Money is an amount in the smallest unit plus a currency, kept as a whole number. Never a float. In the sandbox: the right panel.
- Value Object Domain-driven design
- A small object with no identity that cannot change: two amounts of $10.00 are the same thing. All arithmetic returns a new one. In the sandbox: every amount on the screen.
- Allocation Domain modelling
- To split an amount, divide in whole cents and hand the remaining cents out one by one. The parts always add up. In the sandbox: "1 × $33.34 + 2 × $33.33".
- Strategy Design pattern
- Who gets the remainder, and how tax is rounded, are business rules. Each rule is a separate object that can be replaced and tested. In the sandbox: not drawn; here the first partners get the extra cents.
- Double-entry ledger Accounting
- Every movement is written twice, as a debit and a credit, so a missing cent shows up at once. In the sandbox: the line that stays at $0.00.