# Why float math leaves your client's invoices a cent out

> Picking the right data type solves half the problem; the other half is deciding at which step, and by which rule, money gets rounded.

Original: https://fdetimes.net/en/guides/float-money-rounding-errors-billing/

Type `round(2.675, 2)` into Python and it returns 2.67. Python's official documentation says plainly that this is not a bug. In JavaScript, `(2.55).toFixed(1)` returns `'2.5'`, and MDN explains that the closest float the machine can store sits slightly below 2.55.

Those two lines look trivial until you are the FDE writing a reconciliation script between a client's billing system and the accounting team's ERP. Accountants count every cent. One cent out on a month-end report is enough for them to question every other number you have delivered.

The good news is that the error has a clear root cause and the fixes already exist. The part most often skipped is the step at which rounding happens.

## The computer does not know what 0.1 is

Python's documentation explains that most decimal fractions cannot be represented exactly as binary fractions, so the decimal numbers you enter are usually stored only as approximations. Just as 1/3 cannot be written out in full in decimal, 1/10 cannot be written out in full in binary. The machine stores the nearest value it can.

That is why 2.675 is actually stored as a number a little smaller than 2.675, and `round` rounding down is correct for the number it really received. JavaScript hits the same problem with 2.55, as the `toFixed` example above shows.

The Floating-Point Guide stresses a point that is easy to forget: the 0.1 you type has already been rounded to the nearest number in the binary format before any calculation runs. Every addition and multiplication after that works on a value that is already off, and rounding the final result cannot remove the source of the error.

## Small errors, large sums

Modern Treasury gives an example with a 32-bit float, the type that PostgreSQL's documentation says holds at least 6 decimal digits: it is forced to approximate $25,474,937.47 as $25,474,936.32, a gap of $1.15 caused purely by the data type.

A 64-bit double holds at least 15 digits, so it does not drift that far on this figure, but it is still only an approximation.

So the first rule is simple: money never passes through a float. Modern Treasury stores every amount as an integer in the currency's minor unit, for example cents for USD and EUR, so $12.34 is stored as 1234. Integer addition involves no approximation.

The trap lies in the word "minor". Stripe's API takes `amount` in the smallest unit of each currency: 1000 means 10 USD, but 10 means 10 JPY, because the yen has no fractional unit. An `amount * 100` hard-coded for every currency will charge a Japanese customer 100 times too much.

## Choosing a storage type for each layer

At the database layer, PostgreSQL's documentation specifically recommends `numeric` for monetary amounts and any quantity that requires exactness. When reviewing a client's schema, a money column of type `real` or `double precision` is the first thing worth adding to the risk list.

In code, use an exact decimal type such as Python's `decimal` and pass values in as strings, like `Decimal("1000.00")` in the code below. If you construct it from a float, the value has been approximated before the decimal type ever receives it, so you end up storing a wrong number with perfect precision.

## One invoice, two tax totals

Storing the right type is still not the end, because the step at which you round also changes the result. Stripe gives a neat example: a two-line invoice of $1,000 and $50, with 10% tax included in the price. Recomputed in Python:

```python
from decimal import Decimal, ROUND_HALF_UP

CENT = Decimal("0.01")
lines = [Decimal("1000.00"), Decimal("50.00")]
rate = Decimal("0.10")

def tax_included(gross):
    # the tax portion already contained in a tax-inclusive price
    return gross * rate / (1 + rate)

per_line = sum(tax_included(g).quantize(CENT, rounding=ROUND_HALF_UP)
               for g in lines)
per_invoice = tax_included(sum(lines)).quantize(CENT, rounding=ROUND_HALF_UP)

print(per_line, per_invoice)  # 95.46 95.45
```

The $1,000 line contains $90.9090... of tax, rounded to $90.91. The $50 line contains $4.5454..., rounded to $4.55. Together that makes $95.46. If you add the prices first and then compute tax on $1,050, you get $95.4545..., which rounds to $95.45.

Both are mathematically correct, and Stripe Billing allows both. For invoices using manually entered tax rates, you can either round each line to the minor unit and then add them up, or sum the unrounded taxable amounts for each tax rate and round once at the invoice level.

Stripe Tax keeps full precision throughout the calculation and only rounds half up to the minor unit when determining the amount to collect. If the client's ERP uses one method and your script uses the other, every invoice can end up a cent out.

**Key point:** Ask the accounting team at which step they round before writing your first line of money code.

## Default rounding rules differ

The second source of drift comes from numbers that sit exactly halfway between two values, such as 2.5. Each tool documents its own behavior, and a single pipeline may pass through several of them:

| Tool | When a number sits exactly halfway |
|---|---|
| Python `round()` with built-in types | to the even number, so `round(0.5)` gives 0 and `round(1.5)` gives 2 |
| PostgreSQL `numeric` | away from zero, so 2.5 becomes 3 |
| PostgreSQL `real`, `double precision` | to the nearest even number on most machines, so 2.5 becomes 2 |
| MySQL `ROUND()` with exact numbers | away from zero |
| MySQL `ROUND()` with approximate numbers | depends on the C library; on many systems, to even |
| Stripe Tax | half up |

That is why the code above sets `ROUND_HALF_UP` explicitly, to match the way Stripe Tax rounds. Do not let a library's or database's default make the decision for you: the same transaction can produce two different figures depending on the layer where it is rounded.

When reading FDE job postings, words such as billing, payments, reconciliation or ERP integration signal that you will meet exactly this problem. On a CV, name the concrete work, such as moving money columns from `double` to `numeric` or agreeing a rounding rule with accounting. A generic "handled financial data" says far less.

## What to do on the client site

Start by finding every place money passes through a float: `double` columns, division in JavaScript, `toFixed` in the UI, CSV files read in as floats. Next, settle on one shared representation, either integers in the minor unit or exact decimals, along with a table of decimal places for each currency.

Then comes the conversation with the finance team: round per line or per invoice, half up or half even, and if there is a leftover cent, which line absorbs it. Turn their answers into tests using their own invoice examples.

The four most common mistakes: multiplying by 100 for every currency, building a decimal from a float, rounding only the final result and assuming that is safe, and believing Python's `round()` always rounds 0.5 up.

Finally, reconcile the sum of the lines against the transaction total for every invoice; the grand total on its own proves little. Clients rarely remember how fast you built the pipeline, but they will long remember the first month your report matched the books to the cent.

**Try this week:**

- Grep for float, double, real and toFixed in the billing code of a project you are working on, and note every place a money value passes through a binary type.
- Run the tax calculation in Python from this article, then switch ROUND_HALF_UP to ROUND_HALF_EVEN and find a set of numbers that makes the two totals differ.
- Write three questions about rounding (which step, which rule, which line absorbs the difference) to send the client's finance team at your next discovery session.

## Sources

- [Floating-Point Arithmetic: Issues and Limitations (Python 3 documentation)](https://docs.python.org/3/tutorial/floatingpoint.html)

- [The Floating-Point Guide: Basic Answers](https://floating-point-gui.de/basic/)

- [Built-in Functions (Python 3 documentation)](https://docs.python.org/3/library/functions.html)

- [Number.prototype.toFixed() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)

- [PostgreSQL Documentation: 8.1. Numeric Types](https://www.postgresql.org/docs/current/datatype-numeric.html)

- [Floats Don’t Work For Storing Cents: Why Modern Treasury Uses Integers Instead](https://moderntreasury.com/journal/floats-dont-work-for-storing-cents)

- [Supported currencies | Stripe Documentation](https://docs.stripe.com/currencies)

- [Tax rates | Stripe Documentation](https://docs.stripe.com/billing/taxes/tax-rates)

- [Calculate tax | Stripe Documentation](https://docs.stripe.com/tax/calculating)

- [MySQL 8.4 Reference Manual: Rounding Behavior](https://dev.mysql.com/doc/refman/8.4/en/precision-math-rounding.html)
