Stop your agent doing money maths in floats: pence, an allocate function and properties that keep the books balanced
Agent-written TypeScript splits a 100.00 bill three ways and loses a penny. A small money module, a spec with worked examples and two property checks fix it, in about 15 minutes.

An agent is asked for “split the bill between the diners” and writes this:
export function splitBill(total: number, people: number): number[] {
return Array.from({ length: people }, () => Number((total / people).toFixed(2)));
}
It reads fine and it type-checks. Split 100 three ways and the parts add up to 99.99. The shortfall is one penny, which nobody notices until finance reconciles a month of invoices and finds the ledger and the payment provider disagree by a few hundred pounds across thousands of orders.
Money maths is a place where generated code is confidently wrong in small ways. Floats can’t hold 0.1, toFixed rounds the stored binary value rather than the number you typed, and generated code reaches for price * 1.2 far more readily than for integer arithmetic. The fix isn’t clever. It’s a small module, a spec with worked examples, and two properties that fail loudly when a penny goes missing.
This Playbook builds all three in TypeScript with Vitest and fast-check, then hands them to an agent as the thing it must keep green. It works with any agent that can read files and run a shell. The code, the prompt and the check that proves it worked don’t depend on a particular tool.
What goes wrong, with output
Start with the shape an agent usually produces: prices as number in pounds, VAT as a multiplier, toFixed(2) to tidy up.
export function invoiceTotal(lines: { price: number; qty: number }[], vatRate = 0.2): number {
const net = lines.reduce((sum, l) => sum + l.price * l.qty, 0);
return Number((net * (1 + vatRate)).toFixed(2));
}
Two failures are worth seeing for yourself. In Node 22:
0.1 + 0.2 -> 0.30000000000000004
(1.005).toFixed(2) -> "1.00"
0.7 * 1.05 -> 0.735
Number((0.7 * 1.05).toFixed(2)) -> 0.73
The last line is the one that bites. A 5% VAT charge on a 0.70 net line is exactly 0.735, and the business rule says half a penny rounds up, so the answer is 0.74. The float version prints 0.73 because the stored value sits a hair under 0.735. This isn’t rare. Over every net amount from 0.01 to 1,000.00 in one-penny steps, 1,153 of 100,000 amounts differ between toFixed rounding and exact half-up at 5%. At 20% the problem happens to hide, which is why it survives code review: the one rate everybody tries first is the one that works.
The other failure is allocation. Dividing by three and rounding each part independently can’t sum to the total, because 33.33 times three is 99.99. Someone has to receive the odd penny, and the code has to say who.
The rule that fixes both
Keep money as an integer number of minor units. For sterling that’s pence, 1999 for 19.99. Convert at the edges (parsing a request, formatting a receipt) and nowhere else. Round exactly once, at a named step, with a named rule. Split with a function that distributes the remainder and is built to sum to the total.
That’s the whole idea. The rest of this piece is making it hard for an agent, or a tired human, to drift away from it.
Step 1: write the spec as examples
Before any code, write the behaviour as examples with concrete numbers. These go in a MONEY.md at the repo root, or in the ticket the agent reads. Numbers matter more than prose, because an agent can turn a number into a test and can’t turn “round sensibly” into anything.
Money spec
- Amounts are integer pence. 19.99 is 1999.
- Parsing accepts plain decimals with at most two places: "19.99", "5", "0.5".
It rejects "1.005", "1e3" and "abc" with a RangeError.
- VAT takes net pence and a rate in basis points (2000 = 20%). It rounds half up, once.
vat(1999, 2000) = 400 (399.8)
vat(1, 5000) = 1 (0.5 rounds up)
vat(1, 4999) = 0
- allocate(total, weights) splits by integer weights with the largest-remainder rule.
The parts always sum to total. Ties go to the earlier index.
splitEvenly(10000, 3) = [3334, 3333, 3333]
splitEvenly(-10000, 3) = [-3334, -3333, -3333] (refunds mirror charges)
allocate(1000, [1, 0, 1]) = [500, 0, 500]
- No function in this module uses a non-integer number for money.
The negative case is there on purpose. Refunds go through the same code as charges, and the usual bug is that the odd penny lands on a different person depending on the sign.
Step 2: the module
This is the implementation the spec describes. It’s short enough to read in one go, and that’s a feature: the reviewer’s job becomes confirming that the diff matches the spec rather than reading new arithmetic.
/** Money is an integer count of minor units (pence). Never a float. */
export type Pence = number;
export function parsePence(text: string): Pence {
const m = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(text.trim());
if (!m) throw new RangeError(`Not a money amount: ${JSON.stringify(text)}`);
const pence = Number(m[2]) * 100 + Number((m[3] ?? "").padEnd(2, "0"));
if (!Number.isSafeInteger(pence)) throw new RangeError("Amount too large");
return m[1] === "-" ? -pence : pence;
}
export function formatPence(p: Pence): string {
const sign = p < 0 ? "-" : "";
const abs = Math.abs(p);
return `${sign}${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, "0")}`;
}
/** Rate in basis points (2000 = 20%). Rounds half up, once, at the end. */
export function vat(net: Pence, rateBps: number): Pence {
assertInt(net, "net");
assertInt(rateBps, "rateBps");
return Math.floor((net * rateBps + 5000) / 10000);
}
export function allocate(total: Pence, weights: number[]): Pence[] {
assertInt(total, "total");
if (weights.length === 0 || weights.some((w) => !Number.isInteger(w) || w < 0)) {
throw new RangeError("weights must be non-negative integers");
}
const sum = weights.reduce((a, b) => a + b, 0);
if (sum === 0) throw new RangeError("weights must not all be zero");
const t = Math.abs(total);
const parts = weights.map((w) => Math.floor((t * w) / sum));
let left = t - parts.reduce((a, b) => a + b, 0);
const order = weights
.map((w, i) => ({ i, rem: (t * w) % sum }))
.sort((a, b) => b.rem - a.rem || a.i - b.i);
for (let k = 0; left > 0; k++, left--) parts[order[k].i]++;
return total < 0 ? parts.map((p) => -p) : parts;
}
export const splitEvenly = (total: Pence, ways: number): Pence[] =>
allocate(total, Array<number>(ways).fill(1));
function assertInt(n: number, name: string): void {
if (!Number.isSafeInteger(n)) throw new RangeError(`${name} must be an integer number of minor units`);
}
A few choices deserve a sentence each. vat adds 5000 before the integer division, which is half up in integer form (half of the 10,000 denominator). allocate takes the floor of each share, counts the pence left over, then hands one penny each to the parts with the biggest fractional remainder, earliest index first on a tie. It works on the absolute value and restores the sign at the end, which is what makes the refund mirror the charge. And parsePence uses a regular expression instead of Number("19.99") * 100, because 19.99 * 100 is not 1999 in binary floating point.
Everything is a plain number. That’s safe here because the guards reject anything that isn’t a safe integer, and a pence value up to 2^53 is about 90 trillion pounds. If the domain can exceed that, or needs sub-penny precision for per-unit prices, move to bigint and say so in the spec.
Step 3: tests that pin the examples, then properties
Every example in the spec becomes an assertion. Vitest:
import { describe, expect, it } from "vitest";
import { allocate, formatPence, parsePence, splitEvenly, vat } from "./money";
describe("spec examples", () => {
it("parses and formats without floats", () => {
expect(parsePence("19.99")).toBe(1999);
expect(parsePence("5")).toBe(500);
expect(parsePence("0.5")).toBe(50);
expect(formatPence(1999)).toBe("19.99");
expect(() => parsePence("1.005")).toThrow(RangeError);
expect(() => parsePence("1e3")).toThrow(RangeError);
});
it("rounds VAT half up, once", () => {
expect(vat(1999, 2000)).toBe(400);
expect(vat(1, 5000)).toBe(1);
expect(vat(1, 4999)).toBe(0);
});
it("splits 100.00 three ways without losing a penny", () => {
expect(splitEvenly(10000, 3)).toEqual([3334, 3333, 3333]);
});
it("splits refunds symmetrically", () => {
expect(splitEvenly(-10000, 3)).toEqual([-3334, -3333, -3333]);
});
});
Examples only prove the cases someone thought of. The two properties below cover the rest, using fast-check (4.10.2 at the time of writing, npm i -D fast-check):
import fc from "fast-check";
describe("properties", () => {
const pence = fc.integer({ min: -1_000_000_000, max: 1_000_000_000 });
it("allocation always adds back to the total", () => {
fc.assert(
fc.property(pence, fc.array(fc.integer({ min: 0, max: 1000 }), { minLength: 1, maxLength: 12 }), (t, w) => {
fc.pre(w.some((x) => x > 0));
expect(allocate(t, w).reduce((a, b) => a + b, 0)).toBe(t);
}),
);
});
it("an even split never differs by more than one penny", () => {
fc.assert(
fc.property(pence, fc.integer({ min: 1, max: 50 }), (t, n) => {
const parts = splitEvenly(t, n);
expect(Math.max(...parts) - Math.min(...parts)).toBeLessThanOrEqual(1);
}),
);
});
});
The first property is the one finance cares about: no penny created or destroyed, whatever the weights. The second says fairness has a bound. Neither names a single input, so neither can be satisfied by special-casing the example from the spec, which is a habit agents have when a test is red.
Run it:
npx vitest run
With the module in place, all the tests above pass under Vitest 5.1.0, and npx tsc --noEmit is clean under TypeScript 7.0.2 with strict on.
Step 4: show the properties can fail
A property that can’t fail is decoration. Break allocate on purpose by swapping Math.floor for Math.round in the parts line, and rerun:
Error: Property failed after 8 tests
{ seed: -81502721, path: "7:2:3:0:5:0:5:0:0:1:10:2:1:1:3:16:3:16:2:5:5:6:6:7:5:9", endOnFailure: true }
Counterexample: [469289398,[172,154,431]]
Shrunk 25 time(s)
fast-check found a total of 469,289,398 pence split by weights 172, 154 and 431 where rounding each share up overshoots the total, and shrank the failure to that. The spec example for a three-way split still passed under this breakage, which is the whole argument for properties: the hand-picked case was fine and the bug was real.
The seed and path vary on every run. The counterexample is whichever input fast-check shrank to, so yours will differ. Put the seed in the bug report if you want to replay it.
Step 5: give the agent the spec, the module and a gate
Now the agent comes in, with the examples and properties already in place. A prompt that works with any agent:
Read MONEY.md and src/money.ts. Then change src/invoice.ts so that every
amount is integer pence and uses parsePence, vat, allocate and formatPence from
src/money.ts. Do not do arithmetic on non-integer numbers for money anywhere.
Do not edit src/money.ts or src/money.test.ts. Run `npx vitest run` and
`npx tsc --noEmit` and show me both outputs. If a test fails, fix the calling
code, not the test.
Three details in that prompt carry weight. “Do not edit the module or its tests” stops the most common escape from a red build. Asking for both outputs makes the agent show the check and not describe it. And naming the function names the agent must use turns “be careful with money” into something a reviewer can grep for.
Then spend thirty seconds on the diff, looking for the signs the agent drifted:
.toFixed(orMath.round(near anything that touches an amount.* 100or/ 100outsideparsePenceandformatPence.- A
numberfield namedprice,totaloramountwith no mention of pence in the name or the type. - Changes to the test file that loosen an assertion.
Make it yours
For C# on .NET 10, the same rule maps to long minor units or decimal with an explicit Math.Round(x, 2, MidpointRounding.AwayFromZero) at one named place. decimal avoids the binary-float problem but not the allocation one, so the allocate function and the sum-to-total property still earn their place. Use FsCheck properties in place of fast-check, with xUnit as the runner.
For currencies that don’t have two decimal places, carry the exponent with the amount. A Money object with { minor, currency } stops a pence value being added to a yen value, which a bare number never will.
For card payments, send the provider integer minor units where its API accepts them, and compare your allocation against what the provider reports on settlement. Check the provider’s documentation for the exact field and rounding behaviour; the module here doesn’t know how any one of them rounds.
If the repo already stores money as number pounds, don’t migrate in one pass. Add the module, route new code through it, and add a lint rule that flags .toFixed( in files that import money.ts. Migration is a separate piece of work with its own risk.
What goes wrong
The module doesn’t solve every money problem. It says nothing about currency conversion, tax-inclusive pricing (where you work backwards from a gross price and the rounding rule matters again), or per-unit prices with fractions of a penny. Each of those needs its own spec examples, written with the finance owner and not inferred by the agent.
The rounding rule is a business decision. Half up is common for VAT, but some regimes round per line, some per invoice, and some use banker’s rounding. The spec example vat(1, 5000) = 1 is a claim about your rules, so confirm it with whoever owns them before it becomes a test.
Properties pass vacuously if the generator never produces interesting inputs. The weights here include zeros, large totals and negatives, which is why the tests reach the awkward cases. When you adapt the properties, check the generator can produce a case that fails, which is what Step 4 is for.
And an agent can still do the wrong thing around the module: format a pence value as pounds in an API response, or parse a user-entered “19,99” with a comma. The tests above only cover the module’s own surface, so add an example for each boundary the codebase actually has.
When not to bother: a prototype that never touches real money, a display-only price that’s rounded for show and never summed, or a codebase that already uses a decimal library or a vetted money type. The latter is the better answer; use it, and keep the allocation property as a check against it.
The first 15 minutes
Create a scratch folder, npm init -y, and npm i -D vitest typescript fast-check. Paste in the module and the two property tests, run npx vitest run, then make the Step 4 breakage and watch fast-check find the counterexample. Next, grep your real codebase for .toFixed( and * 1.2: each hit is either display code, which is fine, or arithmetic on money, which is the first thing to move behind vat and allocate.