Series: Numbers & Money lecture 4/6 (intermediate). For developers who have seen rounding go wrong (lecture 3) and now need to store prices, total a cart, split a bill or convert currencies without a one-cent ticket. By the end you will know when to use integer cents and when a decimal type, the traps each decimal type hides in Python, Java, C#, PHP and Swift, and an allocation function that never loses a cent.
Money bugs are rarely dramatic. They are a refund that is one cent short, a CSV export that does not match the payment provider, or a currency field that silently became a float in some layer. This lecture is for the person who has to fix that, and who wants the rules backed by output rather than opinion. Everything below was run on an Apple Silicon Mac (M1 Pro) with Python 3.9.6 (and 3.12 for comparison), Java 26, .NET 10.0.14, PHP 8.5.6 (bcmath, intl with ICU 78.3), Swift 6.4.2, SQLite 3.51.0 and the macOS jsc shell.
Why float is the wrong container for money
Lecture 1 showed that 0.1 has no exact binary form. With money that turns into wrong cents the moment you convert or truncate:
# float_money.py print("sum of ten 0.10 =", sum([0.10] * 10)) print("int(19.99 * 100) =", int(19.99 * 100)) print("round(19.99 * 100) =", round(19.99 * 100)) print("0.07 * 100 =", 0.07 * 100) sum of ten 0.10 = 0.9999999999999999 int(19.99 * 100) = 1998 round(19.99 * 100) = 1999 0.07 * 100 = 7.000000000000001 int() truncates, and 19.99 * 100 is a hair below 1999, so a price of 19.99 became 1998 cents. JavaScript printed 19.99*100 = 1998.9999999999998, and SQLite did the same thing in a query: CAST(19.99*100 AS INTEGER) returned 1998. Converting with round() happens to work here, but now correctness depends on every developer remembering it in every layer.
One SQLite detail surprised us: summing ten rows of 0.10 stored as REAL returned exactly 1.0 in 3.51.0, while Python's plain sum printed 0.9999999999999999. Recent SQLite versions sum floats more carefully. That does not make REAL safe for money; it only means the error shows up somewhere else.
Option 1: integer minor units
The simplest robust rule: store every amount as an integer count of the currency's minor unit. 19.99 USD is 1999; 1,500 JPY is 1500, because the yen has no minor unit in practice; 4,500 KRW is 4500. Addition, subtraction and comparison are then exact, fast and identical in every language and database.
How many minor digits does each currency have? We asked four libraries:
| Currency | Java Currency | .NET CultureInfo | PHP NumberFormatter (ICU 78.3) | jsc Intl |
|---|---|---|---|---|
| JPY | 0 | 0 (ja-JP) | 0 | 0 |
| KRW | 0 | 0 (ko-KR) | 0 | 0 |
| CLP | 0 | 0 (es-CL) | 0 | 0 |
| COP | 2 | 0 (es-CO) | 0 | 2 |
| USD / EUR / MXN | 2 | 2 | 2 | 2 |
| BHD | 3 | (not checked) | (not checked) | (not checked) |
Java's Currency.getDefaultFractionDigits() follows ISO 4217 (COP 2, BHD 3). .NET and PHP formatted 1234.5 Colombian pesos as $ 1.235 with no decimals, while jsc printed $ 1.234,50. So do not derive minor units from a locale formatter: keep your own table, keyed by currency code, and use it both for parsing and display.
A small converter keeps text input from ever touching float:
# cents.py from decimal import Decimal MINOR = {"JPY": 0, "KRW": 0, "CLP": 0, "USD": 2, "EUR": 2, "MXN": 2} def to_minor(text, currency): """'19.99' USD -> 1999; '1500' JPY -> 1500. Refuses more digits than the currency has.""" d = Decimal(text) scaled = d.scaleb(MINOR[currency]) if scaled != scaled.to_integral_value(): raise ValueError(f"{text} has more decimals than {currency} allows") return int(scaled) def show(minor, currency): return f"{Decimal(minor).scaleb(-MINOR[currency]):.{MINOR[currency]}f} {currency}" print(to_minor("19.99", "USD"), to_minor("1500", "JPY"), to_minor("12.5", "EUR")) print(show(1999 * 3, "USD"), show(4500 * 3, "KRW")) try: to_minor("100.5", "JPY") except ValueError as e: print("ValueError:", e) 1999 1500 1250 59.97 USD 13500 KRW ValueError: 100.5 has more decimals than JPY allows Integers have limits too (lecture 2). A signed 64-bit integer holds about 9.2 × 10^18 minor units, which is plenty for prices but not for JavaScript Number, which is exact only up to 2^53. If amounts travel through JSON to a browser, send them as strings or keep them small enough.
Option 2: decimal types, and the trap in each
Integer cents cannot hold 8.25% tax or a unit price of 0.0123. For those steps you need a base-10 type. Each language has one, and each has its own trap.
Python Decimal: build it from strings, never from floats.
# decimal_traps.py import decimal from decimal import Decimal, ROUND_HALF_UP print("Decimal(0.1) =", Decimal(0.1)) print("Decimal('0.1') =", Decimal("0.1")) print("Decimal(0.1) * 3 == Decimal('0.3'):", Decimal(0.1) * 3 == Decimal("0.3")) ctx = decimal.getcontext() print("prec =", ctx.prec, "| rounding =", ctx.rounding) print("Decimal(1) / 3 * 3 =", Decimal(1) / 3 * 3) print("quantize 2.665 ->", Decimal("2.665").quantize(Decimal("0.01")), "| HALF_UP ->", Decimal("2.665").quantize(Decimal("0.01"), ROUND_HALF_UP)) ctx.traps[decimal.FloatOperation] = True # make float leaks loud try: Decimal(19.99) except decimal.FloatOperation as e: print("FloatOperation trapped:", type(e).__name__) Decimal(0.1) = 0.1000000000000000055511151231257827021181583404541015625 Decimal('0.1') = 0.1 Decimal(0.1) * 3 == Decimal('0.3'): False prec = 28 | rounding = ROUND_HALF_EVEN Decimal(1) / 3 * 3 = 0.9999999999999999999999999999 quantize 2.665 -> 2.66 | HALF_UP -> 2.67 FloatOperation trapped: FloatOperation Three lessons: Decimal(0.1) faithfully copies the float error; the default context rounds half-even with 28 significant digits, so quantize without a rounding argument gives 2.66, not 2.67; and division is still inexact. Turning on the FloatOperation trap makes any float that sneaks into a Decimal raise instead of hiding.
Java BigDecimal: equals is not numeric equality.
equals: false compareTo: 0 HashSet size: 2 TreeSet size: 1 stripTrailingZeros equals: true new BigDecimal(0.1) = 0.1000000000000000055511151231257827021181583404541015625 BigDecimal.valueOf(0.1) = 0.1 10 / 3 (scale 2, HALF_EVEN) = 3.33 new BigDecimal("2.0").equals(new BigDecimal("2.00")) is false because equals compares scale too. A HashSet of both amounts had size 2; a TreeSet, which uses compareTo, had size 1. new BigDecimal(0.1) copies the float error, BigDecimal.valueOf(0.1) goes through the shortest string and gives 0.1. Division without a scale throws: new BigDecimal("10").divide(new BigDecimal("3")) printed java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result., and setScale(2) without a rounding mode on 1.005 threw Rounding necessary.
C# decimal: the friendliest of the group, with hard limits.
0.1 + 0.2 == 0.3 (double): False 0.1m + 0.2m == 0.3m: True 1m / 3m * 3m = 0.9999999999999999999999999999 2.0m == 2.00m: True, ToString: 2.0 vs 2.00, Equals: True decimal.MaxValue = 79228162514264337593543950335 OverflowException: Value was either too large or too small for a Decimal. decimal compares by value but keeps the scale for printing, and it always throws on overflow, even outside a checked block (a long wrapped to -9223372036854775808 unless checked).
PHP bcmath: strings in, strings out, and the default scale is 0.
bcmul('19.99','3') = 59 <- default scale 0 bcmul('19.99','3',2) = 59.97 bcdiv('2','3',2) = 0.66 <- truncates bcadd('1e3','1') = ValueError: bcadd(): Argument #1 ($num1) is not well-formed BcMath\Number('19.99') * 3 = 59.97 Forgetting the scale argument silently drops the cents: bcmul('19.99', '3') returned 59. bcdiv truncates rather than rounds, and exponent notation is rejected. PHP 8.4 added the BcMath\Number class, which keeps the scale and supports operators; on 8.5.6 it returned 59.97.
Swift Decimal: the float literal goes through Double first.
Decimal(0.1) = 0.1 Decimal(19.99) = 19.98999999999999488 Decimal(string:"19.99")! * 3 = 59.97 Decimal(0.1) printed 0.1, which makes the trap easy to miss, but Decimal(19.99) printed 19.98999999999999488 and lecture 3's Decimal(1.005) printed 1.0049999999999997952. Use Decimal(string:).
Splitting a bill or a discount without losing a cent
Dividing 100.00 by three cannot give three equal cent amounts. Rounding each share alone loses or creates cents; the largest remainder method fixes it:
# alloc.py import random def allocate(total, weights): """Split integer `total` (minor units) in proportion to `weights`. Largest remainder method: the parts always add up to `total`.""" wsum = sum(weights) parts = [total * w // wsum for w in weights] # floor of each share left = total - sum(parts) # units still to hand out by_rem = sorted(range(len(weights)), key=lambda i: (-(total * weights[i] % wsum), i)) for i in by_rem[:left]: parts[i] += 1 return parts def naive(total, weights): """Round each share half-up on its own (the usual first attempt).""" wsum = sum(weights) return [(2 * total * w + wsum) // (2 * wsum) for w in weights] for total, w, label in [(10000, [1, 1, 1], "$100.00 in 3"), (100000, [1, 1, 1], "100,000 won in 3"), (1000, [480, 980, 1980], "1,000 yen discount over 480/980/1980"), (500, [1, 1, 1, 1, 1, 1], "5.00 EUR over 6 lines"), (7, [1, 1, 1], "7 cents in 3")]: n = naive(total, w) print(f"{label}: naive {n} sum {sum(n)} | allocate {allocate(total, w)} sum {sum(allocate(total, w))}") rng = random.Random(42) T, bad, worst = 100_000, 0, 0 for _ in range(T): w = [rng.randrange(1, 10_000) for _ in range(rng.randrange(2, 8))] total = rng.randrange(100, 1_000_000) d = sum(naive(total, w)) - total if d: bad += 1; worst = max(worst, abs(d)) assert sum(allocate(total, w)) == total print(f"random splits: {T}, naive total wrong in {bad} ({bad / T:.1%}), worst {worst} units; allocate exact in all") $100.00 in 3: naive [3333, 3333, 3333] sum 9999 | allocate [3334, 3333, 3333] sum 10000 100,000 won in 3: naive [33333, 33333, 33333] sum 99999 | allocate [33334, 33333, 33333] sum 100000 1,000 yen discount over 480/980/1980: naive [140, 285, 576] sum 1001 | allocate [139, 285, 576] sum 1000 5.00 EUR over 6 lines: naive [83, 83, 83, 83, 83, 83] sum 498 | allocate [84, 84, 83, 83, 83, 83] sum 500 7 cents in 3: naive [2, 2, 2] sum 6 | allocate [3, 2, 2] sum 7 random splits: 100000, naive total wrong in 31958 (32.0%), worst 3 units; allocate exact in all [[fig:num-money-alloc]]
Naive rounding can go both ways: the yen discount became 1,001, one yen more than promised. Over 100,000 random splits (seed 42) it was wrong 32.0% of the time. The allocation is exact every time and deterministic: ties go to the earlier line, so the same input always gives the same output, which matters when a refund later reverses one line.
Currency conversion: one rate, one rounding
Keep exchange rates as decimal strings, convert with a decimal type, and round once into the target currency's minor unit. The rate below is invented.
# fx2.py from decimal import Decimal as D, ROUND_HALF_UP def q(x, unit="1"): return x.quantize(D(unit), ROUND_HALF_UP) RATE = D("151.37") # invented USD -> JPY rate, kept as a decimal string yen = q(D("19.99") * RATE) print("19.99 USD ->", D("19.99") * RATE, "->", yen, "JPY; back ->", q(yen / RATE, "0.01"), "USD") print("float 19.99 * 151.37 =", 19.99 * 151.37) once = q(D("19.99") * RATE * D("1.10")) # convert + 10% tax, round once twice = q(q(D("19.99") * RATE) * D("1.10")) # round after converting, then again print("with 10% tax: round once", once, "| round twice", twice) items = [D("0.99")] * 100 print("100 x 0.99 USD: convert each line", sum(q(p * RATE) for p in items), "| convert the total", q(sum(items) * RATE)) 19.99 USD -> 3025.8863 -> 3026 JPY; back -> 19.99 USD float 19.99 * 151.37 = 3025.8862999999997 with 10% tax: round once 3328 | round twice 3329 100 x 0.99 USD: convert each line 15000 | convert the total 14986 Rounding twice moved one yen. Converting a hundred 0.99 lines one by one gave 15,000 yen instead of 14,986, because each line rounded 149.8563 up to 150. Decide whether you convert per line or per order, and record the rate and the rounding rule with the transaction so the number can be reproduced later.
Measured: what decimal costs
The usual objection to decimal types is speed. We measured the same job in three languages: 1,000,000 random amounts (seed 42), add 10% tax with half-up rounding to the cent, and sum. Median of 5 runs in Python and 7 in Java and .NET, Apple Silicon Mac (M1 Pro).
# bench.py (Python part) import random, statistics, time from decimal import Decimal as D, ROUND_HALF_UP N, REPS = 1_000_000, 5 rng = random.Random(42) cents = [rng.randrange(1, 100_000) for _ in range(N)] # 0.01 .. 999.99 floats = [c / 100 for c in cents] decs = [D(c).scaleb(-2) for c in cents] CENT, RATE = D("0.01"), D("1.10") def with_int(): return sum((c * 110 + 50) // 100 for c in cents) def with_float(): return sum(round(x * 1.10, 2) for x in floats) def with_dec(): return sum((d * RATE).quantize(CENT, ROUND_HALF_UP) for d in decs) | Language | Integer minor units | Binary float | Decimal type |
|---|---|---|---|
| Python 3.9 | 64.3 ms | 231.7 ms | 173.7 ms (Decimal) |
| Python 3.12 | 54.7 ms | 240.7 ms | 160.3 ms (Decimal) |
| Java 26 | 1.4 ms (long) | 1.6 ms (double) | 22.5 ms (BigDecimal) |
| .NET 10 | 0.9 ms (long) | 1.0 ms (double) | 19.3 ms (decimal) |
[[fig:num-money-speed]]
In Python, Decimal (implemented in C) was faster than float with round(), and integers were fastest. In Java and .NET the decimal types cost 16× and 21× the integer version, yet a million taxed lines still took about 20 ms. For a web request that is noise. It matters in batch jobs over hundreds of millions of rows, which is one more reason to store integers and reach for decimals only in the steps that need them.
The float versions were not just slower in Python, they were wrong: the float total was 124.95 lower than the exact one in Python (12,495 lines one cent low, see lecture 3), 6.83 lower in Java and 7.31 lower in .NET.
Choosing a representation
[[fig:num-money-choose]]
| Need | Use | Watch out for |
|---|---|---|
| Store, add, compare amounts | Integer minor units (BIGINT column) | Currency table for digits; JS Number above 2^53 |
| Tax rates, unit prices with extra decimals | Decimal type built from strings | Decimal(float), scale, default rounding mode |
| Splits, discounts, refunds | Largest remainder on integers | Deterministic tie order |
| Currency conversion | Decimal rate string, round once | Record rate and rule with the transaction |
| Charts, estimates, statistics | float is fine | Never feed the result back into billing |
Common mistakes → what actually happens → fix
| Mistake | What happened in our runs | Fix |
|---|---|---|
int(price * 100) | int(19.99 * 100) → 1998 | Parse the string: to_minor("19.99", "USD") |
Decimal(0.1), new BigDecimal(0.1), Swift Decimal(19.99) | 0.1000000000000000055511151231257827021181583404541015625, 19.98999999999999488 | Construct from strings; enable FloatOperation in Python |
BigDecimal as a map key | HashSet of 2.0 and 2.00 had size 2 | compareTo, or setScale(2) before storing |
bcmul without scale | bcmul('19.99','3') → 59 | Always pass the scale, or use BcMath\Number |
| Each share rounded alone | 100.00 / 3 → 99.99 in total; 32.0% of random splits wrong | Largest remainder allocation |
| Converting per line by accident | 100 × 0.99 USD → 15,000 vs 14,986 JPY | Pick per line or per order on purpose and record it |
| Minor digits from a locale formatter | COP: 2 in Java and jsc, 0 in .NET and PHP | Own currency table keyed by ISO code |
Honest limits and version notes
-
BcMath\Numberwas added in PHP 8.4; we only ran 8.5.6. The minor-unit table reflects ICU 78.3 in PHP, the ICU bundled with .NET 10 and Java 26's currency data; other versions may differ. - The timings are one machine, one job and small N. Java ran from source (
java Bench.java) and .NET withdotnet run -c Release; JIT warm-up was absorbed by taking the median of repeated runs. Java's and .NET's random amounts came from their ownRandom(42), so their totals differ from Python's. - SQLite's exact
1.0for ten summed0.10rows was observed on 3.51.0 only. - Exchange rates and tax rates in the examples are invented or illustrative. Nothing here is accounting, tax or legal advice; your accountant decides the rounding rules.
Exercises
1. A product costs 0.07 USD. A developer computes cents with int(0.07 * 100). Python printed 0.07 * 100 = 7.000000000000001; is int() safe in this case? Name an input from this lecture where the same code fails.
2. Split a 10.00 EUR shared expense in proportion 1 : 1 : 1 : 1 : 1 : 1 : 1 (seven people) with allocate. What does each person get, and which people get the extra cents?
Answers
1. Here it happens to work: 7.000000000000001 truncates to 7. It fails for 19.99: int(19.99 * 100) gave 1998 because the product was just below 1999. Code that works on one price and fails on another is the reason to parse strings instead.
2. 1000 // 7 = 142 cents each, 994 in total, 6 cents left. All remainders are equal, so the tie order hands the 6 cents to the first six people: six get 1.43 EUR and the seventh gets 1.42 EUR, total 10.00. (Same logic as allocate(7, [1, 1, 1]) → [3, 2, 2] above.)
Next
- Previous: Numbers 3/6: rounding modes, banker's rounding and tax
- Next: Numbers 5/6: formatting and parsing numbers across locales
- Integer limits behind "minor units": lecture 2/6, integer overflow and BigInt
- Where JSON numbers change type on the way: PHP prepared statements change JSON number types, JavaScript performance, memory and numbers
- Money columns in a database: SQL basics: SELECT, WHERE and ORDER BY
- Pin allocation with tests: unit testing basics
- All series: programming learning roadmap
Originally published at tlaboratory.net. Every output in this post was copied from a real terminal run.