· 6 min read
Don't Store Money in a Float: Cents, decimal and Rounding Rules
Everyone who learns to program eventually sees 0.1 + 0.2 come out as 0.30000000000000004. In a calculator that is a small display issue; on an invoice it is a bug: a customer is charged one cent too much or too little, and totals stop matching the sum of their lines. This post is about how I stored money and decimal numbers in four of my projects: integer cents in a car rental app, decimal with an explicit rounding rule in a repair shop app, Decimal parsed from strings in a unit converter, and, on purpose, float in a calculator.
The problem: binary floating point
float and double store numbers in base two. Just as 1/3 goes on forever in base ten, 0.1 goes on forever in base two, so it is stored as the nearest value that fits. Python lets you see the value actually stored:
>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> 0.1 + 0.2 == 0.3
False
>>> round(2.675, 2)
2.67
The last one is the most surprising: 2.675 looks like it should round up, but the value in memory is 2.67499999…, so it rounds down. For money, that means the result can be wrong even when the rounding rule is right.
There are two correct ways: store money as an integer in the smallest unit, or use a number type that works in base ten.
1. Car rental (C++): integer cents
In my car rental app, money is a qint64 number of kuruş (the Turkish cent) everywhere:
// Money is stored everywhere as kuruş (an integer):
// 1,250.50 TL = 125050. Storing money as floating point brings rounding errors.
Integer addition and multiplication never make mistakes. The hard part is division and percentages: where does the fraction of a cent go? I wrote that down explicitly wherever it happens:
result.base = dailyPrice * result.days;
result.discount = result.base * result.discountPercent / 100; // integer division: fractions of a kuruş are dropped
result.total = result.base - result.discount;
Integer division drops the fraction. So the discount can come out at most one kuruş lower, and the total always stays consistent as base - discount. Because the rule is written next to the code, nobody has to hunt for "why is there a one-kuruş difference" a year later.
Floating point is touched in only two places: when reading the amount a user typed and when printing it. On the way in, it is rounded to the nearest kuruş:
qint64 fromLira(double lira)
{
return std::llround(lira * 100.0);
}
The double error never enters a calculation: it is converted to kuruş in the first step and left behind.
2. Tamirhane (C#): decimal and rounding per line
Quote lines in Tamirhane, my repair shop app, have a quantity, a unit price, a discount and VAT. Here I used decimal. C#'s decimal works in base ten, so it stores 0.1 exactly:
Console.WriteLine(0.1 + 0.2); // 0.30000000000000004 (double)
Console.WriteLine(0.1m + 0.2m); // 0.3 (decimal)
decimal does not solve rounding; it only makes it visible. With 20% VAT and a 10% discount, intermediate results fall below a cent and have to be rounded somewhere. I made two decisions.
Every step is rounded to 2 places, per line:
public decimal Gross => Money(Quantity * UnitPrice);
public decimal Discount => Money(Gross * DiscountRate / 100m);
public decimal Net => Gross - Discount;
public decimal Vat => Money(Net * VatRate / 100m);
public decimal Total => Net + Vat;
The quote total is the sum of the rounded lines. I don't round the total separately, so a customer adding up the lines by hand gets the same number.
Half a cent rounds away from zero:
internal static decimal Money(decimal amount) => decimal.Round(amount, 2, MidpointRounding.AwayFromZero);
That line matters because .NET's default is different. Without a mode, Math.Round and decimal.Round use banker's rounding: a value exactly halfway goes to the even neighbour.
Math.Round(0.025m, 2); // 0.02
Math.Round(0.025m, 2, MidpointRounding.AwayFromZero); // 0.03
Banker's rounding is a good choice in statistics, because over many operations the ups and downs balance out. But someone who sees 0.025 TL printed as 0.02 on a receipt will think it is a mistake. I picked the rule people expect on a receipt and pinned it with a test:
[Fact]
public void Half_kurus_rounds_away_from_zero()
{
var order = Diagnosing();
// 0.25 × 10% = 0.025 → 0.03
var line = order.AddQuoteLine(QuoteLineKind.Part, null, "Vida", 1, 0.25m, 10, 0).Value;
Assert.Equal(0.03m, line.Vat);
Assert.Equal(0.28m, line.Total);
}
In the database, amounts live in PostgreSQL numeric columns, so they stay in base ten there too. When taking a payment, an amount with digits below a cent (like 10.005 TL) is rejected outright; there is a test for that as well.
3. Unit converter (Python): factors as strings
In the unit converter, every unit has a factor: 1 inch = 0.0254 metres, for example. I used Python's decimal module, but there is a trap here too: writing Decimal(0.0254) carries the float error straight into the Decimal. So the factors are written as strings:
# Factors are written as strings so that converting them
# to Decimal involves no binary floating-point rounding.
unit("in", "in", "İnç", "Inch", "0.0254"),
Exchange rates come from the internet as JSON, and the JSON parser turns numbers into float. There I convert with Decimal(str(value)). str gives the shortest correct representation of a float, so a rate of 34.25 becomes Decimal("34.25"), not 34.249999….
When printing a result I round it to 12 significant digits. Rounding happens only for display; the number is carried in full through the calculation.
4. Calculator (Python): float on purpose
I did not use decimal in the calculator. The reason: scientific functions such as sin, log and square root live in the math module and work on float; Decimal has no equivalent for most of them. This is measurement and science, not money; the real problem is not the calculation but the text the user sees.
Two small things were enough to avoid showing 0.1 + 0.2 as 0.30000000000000004. The result is printed with 15 significant digits:
def format_result(value):
return f"{value:,.15g}"
And a result within a billionth of a whole number snaps to it, so that sin(π) shows 0 instead of 1.2e-16:
def snap_to_integer(x):
nearest = round(x)
return float(nearest) if abs(x - nearest) < 1e-9 else x
That is enough for a calculator, not for money. The difference: in a calculator the error only shows on screen and is fixed in formatting; with money the wrong value gets saved, summed and printed on an invoice.
What I took away
- Money is never stored in
floatordouble. Either an integer in the smallest unit (cents) or a base-ten type (decimal,Decimal,numericin the database). - A base-ten type doesn't solve rounding; it makes it visible. Where to round (per line or on the total) and how (away from zero or to even) has to be chosen explicitly and pinned with a test. In .NET the default is banker's rounding.
- Conversion has to be lossless:
Decimal("0.1"), notDecimal(0.1). A floating-point value from outside is converted in the first step and never goes back tofloatinside the calculation. - An error in display is not an error in calculation. Formatting is enough for a calculator; not for an invoice.