Money in Code: Integer Cents vs Decimal Types
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.
Comments
No comments yet. Start the discussion.