FDE Times dataFDE jobs open 915▼19 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 54Companies hiring 201Remote-friendly 24%Median US pay $200kTop hirer Databricks 109
中文VI

The newspaper of the Forward Deployed Engineer

Guides

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.

ShareLinkedInFacebookX

In brief

  • Binary floats cannot store most decimal fractions exactly, so Python and JavaScript can both round money wrongly in ways their own documentation describes as normal.
  • Store money as integers in the minor unit or as an exact decimal type, and remember that the minor unit for USD and JPY is not the same.
  • On the same invoice, Stripe gets $95.46 in tax when rounding per line and $95.45 when rounding per invoice, so the rounding rule has to be agreed with the client.
Two columns compare the same invoice with two lines of 1000 USD and 50 USD, with 10% tax included in the price. Left column: rounding each line, 90.91 plus 4.55 gives total tax of 95.46 USD. Right column: rounding the whole 1050 USD invoice, 95.4545… becomes 95.45 USD. The two totals differ by one cent.
Rounding tax line by line or across the whole invoice is mathematically sound either way, but the two totals differ by one cent. Source: Stripe's invoice example.

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:

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.

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.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
10 sources
Read next on the roadmap · Stage 1: FoundationsThe API said 202 Accepted. The report still isn't thereA 202 only promises the work will be processed; how long to wait, and when to give up, is left entirely to the client.