Why money should never be a float: integer cents in Ahorreo

Open a browser console and type 0.1 + 0.2. The answer is 0.30000000000000004. Every developer has seen this at some point, laughed, and moved on. In most software it’s harmless. In a personal finance app it slowly eats away at every total on the screen.

When we started building Ahorreo, the first architectural rule we wrote down wasn’t about the UI or the storage layer. It was this: money is an integer number of minor units, always. It is ADR-004 in the project’s decision log, and the project’s own instructions repeat it: never a float, and adding two different currencies has to fail. Here’s why, and what it takes to live with that rule.

The problem with binary fractions

JavaScript numbers are IEEE 754 double-precision floats. They’re binary, and most decimal fractions (0.1 among them) have no exact binary representation, in the same way that one third has no exact decimal one. Every value is rounded to the nearest representable number, and those tiny errors accumulate as you add, subtract and multiply.

For a single sum, the error is invisible once you format to two decimals. But a finance app adds thousands of transactions, scales them by ownership percentages and compares the result with your bank’s balance column. Sooner or later, a total comes out one cent off.

One cent is not a rounding detail

When a computed balance differs from the bank's by €0.01, nobody thinks "floating point". They think "this app is wrong", and every other number on the screen loses its credibility at once.

Three ways floats go wrong

These all run in any browser console, and each one is a mistake that is easy to make when you first parse a bank file.

ExpressionResultWhat went wrong
0.1 + 0.20.30000000000000004Neither operand is exact in binary
ten 0.1s added in a loop0.9999999999999999The error grows with every addition
Math.round(1.005 * 100)1001.005 * 100 is 100.49999999999999, so €1.005 rounds down
(1.005).toFixed(2)"1.00"Same cause, different function
parseFloat("1.234,56")1.234Stops at the comma; €1,234.56 became €1.23

The last one is the most dangerous, because it doesn’t look like a precision problem at all. It looks like a valid number, and it is wrong by a factor of a thousand.

The rule: integers inside a Money type

In Ahorreo, every amount is an integer number of the currency’s smallest unit (cents for euros) inside a small value object. From src/domain/money/money.ts:

export interface Money {
  readonly amountMinor: number;
  readonly currency: CurrencyCode;
}

export function money(amountMinor: number, currency: CurrencyCode): Money {
  if (!Number.isInteger(amountMinor)) {
    throw new TypeError(`Un import ha de ser un enter en unitats mínimes: ${amountMinor}`);
  }
  return { amountMinor: amountMinor === 0 ? 0 : amountMinor, currency };
}

The constructor refuses anything that isn’t an integer, so a float can’t sneak in through arithmetic someone wrote in a hurry. The second line deals with a JavaScript quirk: -0 is a valid integer, and negating a zero balance used to print “-0,00 €”. Now every zero is the same zero.

Integers are exact in JavaScript up to 253 − 1 (Number.MAX_SAFE_INTEGER, 9,007,199,254,740,991). In cents, that’s about ninety trillion euros, comfortably above any household balance we’re likely to meet. Addition and subtraction of integers are exact, so balances computed from ten thousand transactions are exactly the sum of those transactions.

Not every currency has cents. The Japanese yen has no minor unit, so currencyDecimals asks the browser’s Intl.NumberFormat how many decimals each currency uses instead of assuming two. A currency code it doesn’t know falls back to two.

Adding two currencies must fail

The second half of the rule is just as important: adding, subtracting or comparing two Money values in different currencies throws a CurrencyMismatchError. Not a warning, not a silent conversion: an error. If you hold US dollars in a broker and euros in your bank, summing the raw numbers produces a figure that means nothing.

The only correct way to combine them is an explicit conversion at a dated exchange rate. Ahorreo looks for the rate in three places, in order: the effective rate in the statement itself, rates you entered by hand, and a snapshot of ECB rates bundled into the build. If none exists, convert returns null rather than pretending 100 USD is 100 €, and the screen says how many balances were left out. When a figure combines several conversions, it shows the oldest rate date among them, because that is the one that ages the total.

Where the hard work moves: parsing

Using integers doesn’t make the complexity disappear; it pushes it to the edges, where text becomes numbers. Bank statements are inconsistent about how they write amounts, and parseAmountToMinor in src/domain/money/parse.ts handles each of these without passing through a float:

Text in the fileCentsNote
1.234,56 €123456Symbol and spaces stripped
-12,5-1250One decimal digit means fifty cents
(120.00)-12000Parentheses mean negative, accounting style
12,34--1234A trailing minus sign also counts
20.1234562012More decimals than the currency: rounded half up
-20.125-2013The sign is applied after rounding, so halves round away from zero

It strips everything but digits, separators, signs and brackets, decides which character is the decimal separator, removes the thousands separator, pads the fractional part and joins the pieces as a string of digits. Only then does it become a number, and that number is already an integer. The six-decimal case is real: Trade Republic’s CSV writes amounts that way.

Why one cell isn’t enough

Look at 1.234 on its own. With a dot as the decimal separator it’s €1.23; with a comma it’s €1,234.00. A single value can’t tell you which. Parsed alone, Ahorreo’s fallback guess reads it as 123 cents, and that’s why importers don’t parse cell by cell. detectDecimalSeparator scans the whole column first and counts the evidence. A value like 1.234 counts once for each reading, so it cancels itself out; values like 12,50 and -3,10 can only mean a decimal comma, and they decide. Given the column 1.234, 12,50, -3,10, the comma wins and the same 1.234 becomes 123400. A column with nothing but 1.234 stays a tie, and a tie falls back to the dot, which is why the importer shows a preview before saving.

Amounts typed into a form are a third case. There the separator comes from your language setting (decimalSeparatorFor), because the person typing knows what they meant even when the text is ambiguous.

Percentages and rounding, made explicit

Some operations can’t stay exact. Your 50% share of €1.01 is 50.5 cents. Ahorreo has a single function for this, scale, which multiplies and calls Math.round, so rounding happens at one known place and the same input always produces the same cent.

Math.round rounds halves towards positive infinity, and the tests pin down what that means: 101 cents at 50% is 51, and −101 cents at 50% is −50. An odd-cent expense shared in half rounds towards the smaller expense. We kept it that way because it is predictable and tested, but it does mean your half and the other half of an odd-cent bill don’t always add up to the household figure. That’s one reason Ahorreo stores every account, loan and property at 100% and only scales when it displays “my share”: the household total is never rebuilt from rounded halves.

When a total must reconcile, the remainder goes somewhere specific. The mortgage schedule rounds each month’s interest to the cent (Math.round(outstanding * monthlyRate)), and the residue that rounding leaves is assigned to the last instalment, not spread across all of them and not lost. The comment in src/domain/loans/schedule.ts calls it an invariant.

Quantities are not money

The number of fund units or fractional shares you hold isn’t money: it’s a quantity, and it routinely has more than two decimals. Rounding it to cents would lose units. Ahorreo stores quantities as text with eight fixed decimals and does arithmetic on scaled integers (toUnits multiplies by 108 and rounds), for the same reason money is in cents.

Quantities had their own separator bug. The form for editing an operation read what you typed with Number(), and Number("8,25") is NaN. The field seemed to accept the value, saved the string "NaN", and that was read back as zero units. The fix, noted in src/domain/portfolio/quantity.ts, reads typed quantities with your locale’s separator, and a test requires that formatting a quantity and parsing it back returns the same value.

The payoff

This discipline pays for itself in one visible way. When you import a statement that has a balance column, Ahorreo treats the file as a chain: every row’s balance must equal the previous balance plus the row’s amount. From src/domain/accounts/chain.ts:

function holds(rows: readonly ChainRow[]): boolean {
  for (let i = 1; i < rows.length; i += 1) {
    const expected = add(rows[i - 1]!.balance!, rows[i]!.amount);
    if (!equals(expected, rows[i]!.balance!)) return false;
  }
  return true;
}

equals compares two integers, so the check either holds or it doesn’t; there is no tolerance to tune. When it holds, the figures on your screen match your bank’s to the cent. When the balance Ahorreo computes differs from the one in the statement, checkBalance shows the exact difference as an alert, and the comment above it is explicit: never adjusted silently.

Where it still needs care

Integer cents remove a class of bugs; they don’t remove judgement. Three places still need it:

The same integers carry through the rest of Ahorreo: the ownership percentages on shared accounts are applied to cents, and the mortgage calculator on this site keeps its schedule in whole cents too. How the categories on those cents are decided is in Categorising bank transactions without a server, and how the app keeps your data on your device is in Privacy you can test.

This article explains how our software works and the maths behind it. It is not financial, tax or legal advice: for decisions about your own money, check with a qualified professional.