Python money rounding: 8 silent traps in round() and Decimal
TL;DR: Do not store money in a float, and do not call quantize on a Decimal that inherited the default context. The three most expensive divergences below are: round() sends exact halves to the even neighbour instead of away from zero; the default 28-digit precision silently drops digits; and for splits or per-unit tax, when you round matters more than how you round.
The eight divergences in one line each
round()is not round-half-up: exact halves go to the even neighbour, soround(0.5)is 0 andround(2.5)is 2.- The same 2.675 has three answers:
f'{2.675:.2f}'gives 2.67,Decimal(str(2.675))quantized gives 2.68, andDecimal(2.675)quantized goes back to 2.67. - Feeding a float to Decimal feeds it a binary tail:
Decimal(0.1)has 55 decimal places and is not equal toDecimal("0.1"). - 28 digits vanish silently:
Decimal("1e30") + 1equalsDecimal("1e30")and the comparison returns True with no warning. quantizereads the rounding mode from the thread context:round(Decimal("2.665"), 2)is 2.66 by default and 2.67 the moment the context changes.- Mixing Decimal and float is a half-open door: addition raises TypeError, while comparison and sorting let everything through.
- A split that does not divide evenly is always a cent short: 100 divided three ways rounds to 33.33 each, and the three add up to 99.99.
- Neither JSON nor sqlite3 accepts a Decimal: one raises TypeError, the other ProgrammingError, and both fail far from the money logic.
None of this is copied from documentation prose. Every number below is output from my own machine, and every snippet can be pasted and re-run.
What I actually tested
CPython 3.13.14 on Windows 11, using only the standard library (decimal, json, sqlite3). I tested four script batches, all with zero dependencies, zero credentials and zero network calls. Where I quote official documentation I mark it as a quote rather than paraphrase it.
Money figures like $19.99 appear only to make the arithmetic concrete. There are no affiliate links in this article and I am not recommending any product.
Divergence 1: round() is not round-half-up
The official docstring for round() is explicit:
"The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative."
So round(x) gives you an int and round(x, 2) gives you a float or a Decimal. That alone is worth knowing: the two call forms return different types, and dropping both into the same list sorts without complaint while an isinstance(x, float) branch downstream quietly takes the wrong path.
The real divergence is at exact halves. Measured on this machine:
round(0.5) # 0
round(1.5) # 2
round(2.5) # 2
round(-1.5) # -2
round(-0.5, 0) # -0.0
Note the last line: round(-0.5) with ndigits omitted returns the int 0, while round(-0.5, 0) returns the float -0.0. One number, one function, one extra argument and you have a negative zero. That negative zero serializes to JSON as -0.0, prints in a report as "-0.00", and fails a string comparison against 0.0.
This rule has an official name. The decimal module documents ROUND_HALF_EVEN as "Round to nearest with ties going to nearest even integer." That also explains why round(1.5) is 2 and round(2.5) is also 2: 2 is even, so 2.5 steps down.
The business consequence is not "an occasional cent". It is systematic bias. If every invoice ends in .5, the whole ledger drifts toward even digits, and positive and negative drift do not cancel out to zero. When an auditor asks why the total is 3.5 short of the line items, "that is just how Python works" is not an answer.
There is a second layer underneath, and it is worse: even if you accept half-even, round() on a float can still produce a result that is wrong by decimal intuition. That is the next divergence.
Divergence 2: one number, three call paths, two answers
I ran three formulations that all look correct, on the same machine:
f'{2.675:.2f}' # '2.67'
Decimal(str(2.675)).quantize(Decimal('0.01')) # Decimal('2.68')
Decimal(2.675).quantize(Decimal('0.01')) # Decimal('2.67')
The first gives 2.67 and the second gives 2.68. Both claim to render the same number to two places, and they disagree by a cent.
The reason lives inside the float. format(2.675, '.20f') prints 2.67499999999999982236, so the stored value is below 2.675. There is no tie at all, and half-even never gets a vote; anything that rounds to nearest must go down. Meanwhile str(2.675) returns the shortest round-trip representation '2.675', so Decimal('2.675') is exactly 2.675 and the tie is real: the digit being dropped is 7, 7 is odd, so half-even steps up to 8.
The same business rule therefore produces three different "correct" answers depending on which layer you ask:
- At the float layer,
f'{x:.2f}'faithfully reports the binary value and says 2.67. - At the string-capture layer,
Decimal(str(x))treats the shortest representation as truth and says 2.68. - At the exact-conversion layer,
Decimal(x)recovers the full 53-bit tail and says 2.67 again.
Change the input and the disagreement flips direction. 1.115 formats to 1.11 but Decimal(str(1.115)) quantizes to 1.12. 1.005 loses the tie under half-even and gives 1.00, but ROUND_HALF_UP makes it 1.01.
My conclusion is blunt: do not argue about rounding rules on a float. The number 2.675 does not exist inside a float; only a neighbour does. If the decision has to be made in decimal semantics, the data has to be decimal before it reaches the decision.
Divergence 3: Decimal(float) is not Decimal("0.1")
The documentation says this itself. From the Decimal.from_float() note:
"Note Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. That equivalent value in decimal is 0.1000000000000000055511151231257827021181583404541015625."
The constructor section adds that a float is "losslessly converted to its exact decimal equivalent", and that "This conversion can often require 53 or more digits of precision."
On this machine:
Decimal(0.1) # 0.1000000000000000055511151231257827021181583404541015625
Decimal('0.1') # 0.1
Decimal(0.1) == Decimal('0.1') # False
Fifty-five decimal places, diverging around the eighteenth. The error is tiny, invisible to any rounding at two decimal places, so why does it matter?
Because it surfaces exactly where nobody looks: a grouped sum compared for equality against another grouped sum, a quantity times a unit price reconciled against a ledger, money pushed into a set or used as a dict key, or a value bound as a SQL parameter and matched against a DECIMAL column. Decimal(0.1) == Decimal("0.1") returns False, and that one line has burned plenty of afternoons on tickets where "both sides are obviously 0.1".
There is exactly one fix: convert money to a string or to integer cents at the boundary, and never let a float in. Read CSV with the csv module so you get strings instead of letting a dataframe library infer floats. Read JSON with json.loads(..., parse_float=str). Read spreadsheet cells as text and validate the format yourself.
Divergence 4: 28 digits disappear without a trace
The default context, quoted from the docs:
"The default values are Context.prec=28, Context.rounding=ROUND_HALF_EVEN, and enabled traps for Overflow, InvalidOperation, and DivisionByZero."
Twenty-eight digits is plenty for ordinary money. The problem is that "plenty" is conditional, and when the condition fails nothing raises:
Decimal('1e30') + Decimal('1') == Decimal('1e30') # True
The addition swallowed the 1. The result is still a perfectly valid Decimal, and the comparison is "correctly" equal. This is nearly impossible to catch in unit tests: you write assert total == expected, both sides lose the same digit to the same context rule, and the assertion stays green.
Shrinking the precision makes the failure cascade. I set the context precision to 6 and ran an ordinary addition:
with localcontext() as ctx:
ctx.prec = 6
s = Decimal('123456.78') + Decimal('1.00') # 123458
s.quantize(Decimal('0.01')) # decimal.InvalidOperation
The sum is 123458, the entire fractional part is gone (as_tuple() reports digits=(1,2,3,4,5,8), exponent=0), and the very next quantization raises InvalidOperation. One line is silent, the next crashes, and the cause sits two lines above both.
The docs are restrained about this in the section titled "Mitigating round-off error with increased precision": decimal eliminates decimal representation error, but "some operations can still incur round-off error when non-zero digits exceed the fixed precision."
A rule you can apply: minimum precision is integer digits, plus decimal places, plus the longest decimal tail of any rate or multiplier, plus one spare digit. A two-decimal amount multiplied by a four-decimal tax rate, with balances up to a billion (10 integer digits), needs 10 + 2 + 4 + 1 = 17 digits, and 28 is comfortable. But compound interest, unit conversion (milligrams to tonnes, thousandths to units) or a chain of multiplications will cross the line quickly, and then you must set localcontext(prec=...) explicitly instead of trusting the default.
Divergence 5: quantize reads the thread context
Identical source text, different result, because the context changed underneath it:
round(Decimal('2.665'), 2) # 2.66
with localcontext() as ctx:
ctx.rounding = ROUND_HALF_UP
round(Decimal('2.665'), 2) # 2.67
round(Decimal('2.665'), 2) # 2.66
quantize() behaves the same way when rounding= is omitted. It reads the current context; it does not mean "round half up" and it does not mean "same as last time".
Why is 2.665 rounded to 2.66? Half-even looks at what follows the digit being dropped. 2.665 is exactly a half, with nothing non-zero after the 5, so the rule inspects the preceding digit: 6 is even, so it stays. For 1.005 the preceding digit is 0, also even, so it becomes 1.00 rather than 1.01. One rule, one case that "looks rounded" and one that "looks untouched", decided entirely by parity.
Contexts are thread-local, and the docs are explicit about the scope: "The getcontext() function accesses a different Context object for each thread. Having separate thread contexts means that threads may make changes (such as getcontext().prec=10) without interfering with other threads."
Read that carefully. It is a promise about other threads, not about yours. Every line of code on the same thread shares that context, including third-party libraries and the helper you wrote three months ago that set prec to 10. Asyncio makes it worse: many coroutines run on one thread, so a coroutine that mutates the context hands the mutated version to whatever runs next.
So: never write a bare quantize(Decimal('0.01')) in financial code. Either pass rounding=ROUND_HALF_UP explicitly, or wrap the whole function in localcontext() and set both prec and rounding. Being explicit beats being right, because you cannot know what the caller's context already is.
One correction while we are here: ROUND_HALF_UP is defined as "Round to nearest with ties going away from zero." Away from zero, not the schoolbook intuition for negative numbers. Decimal('-2.5') becomes -3 under HALF_UP and -2 under HALF_DOWN. Refunds and reversals need their own test pass.
Divergence 6: mixing Decimal and float is a half-open door
Decimal('0.1') + 0.1 # TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'
Decimal('0.1') == 0.1 # False
Decimal('0.1') != 0.1 # True
sorted([0.3, Decimal('0.2'), 0.1]) # [0.1, Decimal('0.2'), 0.3]
Addition refuses outright, while comparison and sorting wave everything through. And the comparison is not merely "not equal": the float 0.1 is slightly larger than decimal 0.1, so a size comparison concludes that the Decimal side is smaller. Put that in a credit-limit check and you either let through a value you should have rejected or reject one you should have kept, depending on which side of the comparison your data lands.
sorted() mixing types is the more dangerous one. A list of [float, Decimal, float] sorts quietly and the return value shows no sign of trouble. The crash arrives later, when a Decimal meets a Decimal, several frames away from where the mixing happened.
Decimal('1.0') equals the int 1 and the float 1.0, and hashes identically, so it will hit a {1.0: ...} dictionary key directly. That is convenient for caching and a hazard when money is the key: Decimal('1.00') and Decimal('1.0') collapse into one key even though you meant to distinguish two precisions.
The module gives you a way to turn mixing into a hard error, the FloatOperation signal:
"If the signal is not trapped (default), mixing floats and Decimals is permitted in the Decimal constructor, create_decimal() and all comparison operators. Both conversion and comparisons are exact."
With the trap enabled, both Decimal(0.1) and sorted([0.3, Decimal('0.2')]) raise FloatOperation on this machine. That one line at the entry point of a finance module is the highest-value configuration I know of here: mixing becomes a crash at startup instead of a reconciliation failure three months later.
Divergence 7: splitting 100 three ways loses a cent
total = Decimal('100.00')
raw = total / 3 # 33.33333333333333333333333333
naive = raw.quantize(Decimal('0.01')) # 33.33
naive * 3 # 99.99
Three people get 33.33 each and the total is 99.99. The cent does not evaporate; it becomes a statement that never balances.
The fix is the largest remainder method: allocate the floor of each share, then distribute the remaining minimum units by descending fractional remainder. On this machine that yields 33.34 + 33.33 + 33.33 = 100.00. Who receives the extra cent has to be a documented rule (usually the largest remainder, or the first beneficiary), not a judgement call made at runtime.
Per-unit tax drifts further:
price = Decimal('19.99'); rate = Decimal('0.0825')
(price * (1 + rate)).quantize(Decimal('0.01')) # 21.64 (per unit)
(price * 100 * (1 + rate)).quantize(Decimal('0.01')) # 2163.92 (sum first)
Decimal('21.64') * 100 # 2164.00 (round first)
One hundred units at the same price, and the two orderings disagree by $0.08. That sounds negligible until you notice it is eight cents per hundred units, which is roughly $800 of unexplained variance per million units, always in the same direction: the round-first side is always higher.
Which means when you round is more expensive than how you round. A wrong mode gives you noise; a wrong moment gives you bias. The rule for your code: do not round intermediate values, and never persist an unrounded final value.
Divergence 8: serialization is the last gate
Money can be perfectly correct in memory and still fail on the way out.
json.dumps({'amount': Decimal('1.10')})
# TypeError: Object of type Decimal is not JSON serializable
conn.execute('insert into t values (?)', (Decimal('1.10'),))
# sqlite3.ProgrammingError: Error binding parameter 1: type 'decimal.Decimal' is not supported
Both errors are loud, and the trouble is the workaround people reach for. To get past JSON many write float(amount), and 1.10 becomes its binary neighbour. To get past sqlite3 many write float(amount) too; I measured the stored typeof() as real, 1.10 reads back as 1.1, and one more operation can turn it into 1.1000000000000001.
There is also a split between display and comparison:
Decimal('1.00') == Decimal('1.0') # True
hash(Decimal('1.00')) == hash(Decimal('1.0')) # True
str(Decimal('1.00')) # '1.00'
Decimal('1.00').as_tuple() # digits=(1, 0, 0), exponent=-2
Decimal('1.0').as_tuple() # digits=(1, 0), exponent=-1
Equal, same hash, different strings, different as_tuple(). In other words: comparison drops trailing zeros, display keeps them. If you display with str() and validate with equality, the two are not checking the same thing. Conversely, this is where Decimal beats float: it remembers that the value is two decimal places, so trailing zeros in a money field survive the round trip.
For implementation: store integer cents (BIGINT) or a NUMERIC(18,2) column with Decimal on the application side, send money as strings in JSON, and write an explicit encoder instead of leaving it to a convenient float().
Troubleshooting: six errors I actually hit
All six were reproduced on this machine, not copied from documentation examples.
- TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float' — mixed arithmetic. Fix the types at the source, or enable the
FloatOperationtrap at module entry so it fails at startup instead of at reconciliation. - decimal.InvalidOperation — two distinct causes here. One is a quantization whose result exceeds the context precision:
Decimal('1e30').quantize(Decimal('0.01'))always raises under prec=28, whileContext(prec=40)returns 1000000000000000000000000000000.00. The other is a NaN in a comparison:min(Decimal('NaN'), Decimal('1'))raises immediately. The exception text embeds a class name string and reads like an unhandled internal error, but it is a normal signal. - decimal.DivisionByZero — division by zero. Note that its MRO is
DivisionByZero, thenDecimalException, thenZeroDivisionError, soexcept ZeroDivisionErrordoes catch it, whiletype(e).__name__still prints DivisionByZero in your logs.except decimal.DecimalExceptionis the better net: it covers InvalidOperation, DivisionByZero and Overflow, all three defaults. - decimal.Overflow — float returns
infhere; Decimal raises by default.Decimal('1e999999') * Decimal('1e999999')raises Overflow on this machine. Its MRO also includes Inexact and Rounded, which means anexcept decimal.Inexacthandler will quietly classify an overflow as "not exact" — a genuinely funny trap. - FloatOperation — appears only when the trap is enabled, and then even
Decimal(0.1)raises, because construction itself counts as mixing. Put this in the project conventions or a colleague will file it as a bug. - JSON's TypeError and sqlite3's ProgrammingError — the two from the previous section. The fix is a string or integer cents, not
float().
A checklist you can copy
- Entry: money arrives as a string or integer cents; use
json.loads(..., parse_float=str), read CSV as text, read spreadsheet cells as text. - Construction: always
Decimal(str(x)), neverDecimal(float_x); when an ORM hands you a float, convert throughstr()and log once, because it means a float leaked upstream. - Precision: set
localcontext(prec=...)explicitly on entry to every financial function, with a floor of integer digits, decimal places, longest multiplier tail and one spare. - Rounding: every
quantizepassesrounding=explicitly; verify negative amounts (refunds, reversals) separately against the away-from-zero semantics of HALF_UP. - Timing: no rounding of intermediates; anything persisted or reconciled is already aligned; each business event is rounded exactly once.
- Splits: largest remainder for the residual, the allocation rule written down, and an assertion that the parts sum to the whole.
- Mixing:
getcontext().traps[decimal.FloatOperation] = Trueat the finance module entry point. - Storage and transport: BIGINT cents or NUMERIC(18,2) in the database, strings in JSON,
str()in logs rather thanfloat().
This checklist does not solve everything (currencies, rate dates and tax rules sit outside it), but it blocks all eight divergences above.
FAQ
Q: Can a money field be a float if it is only ever displayed?
If the value never enters arithmetic, never takes part in an equality check and never lands in an aggregation, a float is fine. The moment it might be summed, sorted, deduplicated or compared against another record, use Decimal. The test is cheap: ask whether the field can appear in a GROUP BY or in an equality comparison.
Q: How much precision does Decimal need?
Work out integer digits, plus decimal places, plus the longest decimal tail of any multiplier, plus one. That is a floor, not a recommendation. A typical two-decimal store with billion-scale balances and a four-decimal tax rate needs 17 digits. If you do unit conversion or compound interest, walk the actual chain and then round up to a multiple of ten. Setting it higher costs a few bytes and loses no accuracy.
Q: Why is 1.005 rounded to 1.01 by ROUND_HALF_UP but to 1.00 by an f-string?
The f-string is working on the float 1.005, which is actually stored as 1.00499999999999989342 — below the halfway point, so every rule rounds down. Decimal('1.005') is an exact half, so HALF_UP steps away from zero. This is not a Python bug; it is the unavoidable difference between binary and decimal representations.
Q: Is there a library that avoids all this?
The standard library is enough; the usage is what matters. A finance library can wrap splitting and currencies, but it cannot wrap these eight divergences, because they live on the Decimal-to-float boundary rather than in business logic. Manage the boundary first, then talk about abstraction.
Closing
The eight divergences share one shape: the code does not raise, the answer is wrong, and it is wrong by a very small amount. Small enough that tests miss it, small enough that it surfaces three months after launch, small enough that nobody wants to touch the fix.
This is not a Python-only problem either. Any language that represents decimal money in binary floating point has the same traps; Python just puts both numeric types in front of you and lets you believe that choosing Decimal made you safe. What actually decides the result is three things: where the data came from, whose context is active, and at which step you rounded.
I have written two adjacent pieces on this line: one on SQL's three-valued NULL logic, where the denominator goes wrong, and one on Unicode normalization, where the problem is that two values look identical. Together with the last digit in this piece, they describe the same thing: values deform at boundaries, and boundaries are not written in type signatures. The serialization layer gets its own treatment in my json, orjson and msgspec defaults comparison.
👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference
👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation
📌 This article was AI-assisted generated and human-reviewed | TechPassive — An AI-driven content testing site focused on real tool reviews
🔗 Recommended Tools
These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:
As an Amazon Associate, I earn from qualifying purchases at no extra cost to you.