Decimal and fractions
suggest changePython's float is a binary floating-point number. It's fast and good enough for science and graphics, but it can't represent most decimal fractions exactly. Usually that doesn't matter. For money, or anywhere results have to match what a person would get with pencil and paper, it does.
The standard library has two exact alternatives:
decimal.Decimal: decimal floating point with a precision and rounding mode you choose. Use it for money, prices, taxes and anything specified in decimal digits.fractions.Fraction: exact rational numbers stored as numerator and denominator. Use it when you need exact results for ratios such as 1/3.
This article covers:
- why
0.1 + 0.2 != 0.3and when that matters - creating
Decimalvalues correctly (strings, not floats) quantizeand rounding modes for money- contexts: precision, traps and local contexts
Fractionarithmetic,limit_denominatorand converting between types- mixing the numeric types and the performance cost
The problem with float
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(1.1 * 3)
total = 0.0
for _ in range(10):
total += 0.1
print(total)
0.30000000000000004
False
3.3000000000000003
0.9999999999999999
0.1 has no exact binary representation, so Python stores the closest 53-bit binary fraction. Passing a float to Decimal shows the value that's actually stored:
from decimal import Decimal
print(Decimal(0.1))
0.1000000000000000055511151231257827021181583404541015625
Rounding to 2 places often gives surprising results for the same reason. 2.675 is really stored as slightly less than 2.675:
from decimal import Decimal
print(round(2.675, 2))
print(Decimal(2.675))
2.67
2.67499999999999982236431605997495353221893310546875
For comparing floats approximately, math.isclose() is the right tool. When you need exact decimal results, use Decimal. See Rounding round floor ceil trunc for the basics of rounding floats.
Creating Decimal values
Create a Decimal from a string or an int. A string keeps exactly the digits you wrote:
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
print(Decimal(42))
print(Decimal("1.50"))
print(Decimal("-3.14e2"))
print(Decimal(" 7.25 "))
0.3
True
42
1.50
-314
7.25
Note that Decimal("1.50") keeps the trailing zero. A Decimal remembers its exponent, which is what lets money amounts print as 1.50 rather than 1.5.
Avoid creating a Decimal from a float. You get the float's exact binary value, which is precisely the error you were trying to escape. If you do have a float, go through str(), which gives the shortest representation that round-trips:
from decimal import Decimal
price = 19.99
print(Decimal(price))
print(Decimal(str(price)))
19.989999999999998436805981327779591083526611328125
19.99
You can make float construction an error with the FloatOperation trap, described in the contexts section below.
Invalid strings raise decimal.InvalidOperation:
from decimal import Decimal, InvalidOperation
try:
Decimal("12,50")
except InvalidOperation as e:
print("invalid:", type(e).__name__)
invalid: InvalidOperation
Special values are supported too:
from decimal import Decimal
print(Decimal("Infinity"), Decimal("-inf"), Decimal("NaN"))
print(Decimal("Infinity") > Decimal("1e1000"))
Infinity -Infinity NaN
True
Arithmetic
Decimal supports the usual operators and works with ints directly:
from decimal import Decimal
a = Decimal("10.25")
b = Decimal("3")
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b, a % b)
print(a ** 2)
print(a * 2, 2 + a)
13.25
7.25
30.75
3.416666666666666666666666667
3 1.25
105.0625
20.50 12.25
Division produces as many digits as the current precision allows (28 significant digits by default).
Two details differ from ints. // truncates toward zero and % takes the sign of the dividend, so negative numbers behave differently than with int:
from decimal import Decimal
print(-7 // 2, -7 % 2)
print(Decimal(-7) // 2, Decimal(-7) % 2)
-4 1
-3 -1
The Decimal class also has math methods:
from decimal import Decimal
d = Decimal(2)
print(d.sqrt())
print(d.ln())
print(d.exp())
print(Decimal(1000).log10())
print(Decimal("-4.5").copy_abs())
1.414213562373095048801688724
0.6931471805599453094172321215
7.389056098930650227230427461
3
4.5
Functions from the math module accept a Decimal, but they convert it to float first, so the result is a float and the precision is lost.
Rounding with quantize
round() works on Decimal and uses banker's rounding (round half to even), like it does for floats:
from decimal import Decimal
print(round(Decimal("2.675"), 2))
print(round(Decimal("2.665"), 2))
print(round(Decimal("2.5")))
2.68
2.66
2
For money you usually want explicit control over the rounding rule. quantize() rounds a value to the exponent of another decimal, and takes a rounding argument:
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
CENTS = Decimal("0.01")
x = Decimal("2.665")
print(x.quantize(CENTS))
print(x.quantize(CENTS, rounding=ROUND_HALF_EVEN))
print(x.quantize(CENTS, rounding=ROUND_HALF_UP))
print(Decimal("7").quantize(CENTS))
print(Decimal("1234.5").quantize(Decimal("1")))
2.66
2.66
2.67
7.00
1234
The default rounding mode is ROUND_HALF_EVEN. Note that quantize also pads: Decimal("7") becomes 7.00.
All rounding modes, applied to a few values:
from decimal import Decimal
import decimal
modes = ["ROUND_HALF_UP", "ROUND_HALF_EVEN", "ROUND_HALF_DOWN",
"ROUND_UP", "ROUND_DOWN", "ROUND_CEILING", "ROUND_FLOOR", "ROUND_05UP"]
values = ["2.5", "3.5", "-2.5", "2.4", "-2.6"]
print(f"{'':16}" + "".join(f"{v:>6}" for v in values))
for m in modes:
mode = getattr(decimal, m)
row = [str(Decimal(v).quantize(Decimal("1"), rounding=mode)) for v in values]
print(f"{m:16}" + "".join(f"{r:>6}" for r in row))
2.5 3.5 -2.5 2.4 -2.6
ROUND_HALF_UP 3 4 -3 2 -3
ROUND_HALF_EVEN 2 4 -2 2 -3
ROUND_HALF_DOWN 2 3 -2 2 -3
ROUND_UP 3 4 -3 3 -3
ROUND_DOWN 2 3 -2 2 -2
ROUND_CEILING 3 4 -2 3 -2
ROUND_FLOOR 2 3 -3 2 -3
ROUND_05UP 2 3 -2 2 -2
ROUND_UP and ROUND_DOWN round away from and toward zero. ROUND_CEILING and ROUND_FLOOR round toward positive and negative infinity. ROUND_HALF_UP is what most people learned in school. ROUND_HALF_EVEN avoids a systematic upward bias when rounding many values, which is why it's common in finance.
A money example
A typical pattern: keep all amounts as Decimal, do the arithmetic at full precision, and round once at well-defined points (per line item, or on the total, depending on your business rules).
from decimal import Decimal, ROUND_HALF_UP
CENTS = Decimal("0.01")
def money(value: str | int | Decimal) -> Decimal:
return Decimal(value).quantize(CENTS, rounding=ROUND_HALF_UP)
items = [
("Coffee", Decimal("3.45"), 3),
("Bagel", Decimal("2.10"), 2),
("Juice", Decimal("4.99"), 1),
]
tax_rate = Decimal("0.0825")
subtotal = sum((price * qty for _, price, qty in items), Decimal(0))
tax = money(subtotal * tax_rate)
total = subtotal + tax
for name, price, qty in items:
print(f"{name:8} {qty} x {price:>6} = {price * qty:>7}")
print(f"{'Subtotal':>20} {subtotal:>8}")
print(f"{'Tax':>20} {tax:>8}")
print(f"{'Total':>20} {total:>8}")
Coffee 3 x 3.45 = 10.35
Bagel 2 x 2.10 = 4.20
Juice 1 x 4.99 = 4.99
Subtotal 19.54
Tax 1.61
Total 21.15
sum() is given a Decimal(0) start value. Without it sum() starts from the int 0, which also works but then returns int 0 for an empty list instead of a Decimal.
Splitting an amount evenly is another classic. Dividing and rounding each share loses or invents cents; distribute the remainder instead:
from decimal import Decimal, ROUND_DOWN
def split(total: Decimal, n: int) -> list[Decimal]:
cents = Decimal("0.01")
share = (total / n).quantize(cents, rounding=ROUND_DOWN)
remainder = total - share * n
extra = int(remainder / cents)
return [share + cents if i < extra else share for i in range(n)]
parts = split(Decimal("100.00"), 3)
print(parts)
print(sum(parts))
[Decimal('33.34'), Decimal('33.33'), Decimal('33.33')]
100.00
Formatting Decimal
Decimal supports the same format specifications as float, without converting to float:
from decimal import Decimal
d = Decimal("1234567.891")
print(f"{d:.2f}")
print(f"{d:,.2f}")
print(f"{d:>15,.1f}")
print(f"{Decimal('0.0825'):.2%}")
print(f"{Decimal('12345.6789'):.3e}")
1234567.89
1,234,567.89
1,234,567.9
8.25%
1.235e+4
str() and repr() give the exact stored value, and normalize() strips trailing zeros (beware it switches to exponent notation for whole numbers with trailing zeros):
from decimal import Decimal
d = Decimal("12.3400")
print(str(d), repr(d))
print(d.normalize())
print(Decimal("1200").normalize())
print(f"{Decimal('1200').normalize():f}")
12.3400 Decimal('12.3400')
12.34
1.2E+3
1200
More on format specifiers in Float formatting.
Contexts: precision, rounding and traps
Arithmetic operations use the current context, which holds the precision (in significant digits, not decimal places), the default rounding mode and which conditions raise exceptions:
from decimal import Decimal, getcontext
ctx = getcontext()
print(ctx.prec, ctx.rounding)
ctx.prec = 6
print(Decimal(1) / Decimal(7))
print(Decimal("123456789") + 0)
ctx.prec = 28
28 ROUND_HALF_EVEN
0.142857
1.23457E+8
Precision applies to results of operations, not to values you construct: Decimal("123456789") keeps all its digits until you compute with it.
Changing getcontext() affects all code in the current thread (and asyncio task), which is easy to get wrong. Prefer localcontext(), which restores the previous context when the block exits:
from decimal import Decimal, localcontext
with localcontext() as ctx:
ctx.prec = 50
print(Decimal(2).sqrt())
print(Decimal(2).sqrt())
with localcontext(prec=10):
print(Decimal(1) / Decimal(3))
1.4142135623730950488016887242096980785696718753769
1.414213562373095048801688724
0.3333333333
Passing settings as keyword arguments to localcontext() requires Python 3.11 or newer.
Traps
Conditions like division by zero or an inexact result are signals. If a signal is enabled in ctx.traps, it raises an exception; otherwise only a flag is set. By default DivisionByZero, InvalidOperation and Overflow raise:
from decimal import Decimal, DivisionByZero
try:
Decimal(1) / Decimal(0)
except DivisionByZero:
print("division by zero")
print(Decimal(0) / 1)
division by zero
0
Enabling the FloatOperation trap makes it an error to build a Decimal from a float or to mix floats and decimals in comparisons. Turning it on is a cheap way to catch accidental floats in money code:
from decimal import Decimal, FloatOperation, localcontext
with localcontext() as ctx:
ctx.traps[FloatOperation] = True
print(Decimal("1.1"))
try:
Decimal(1.1)
except FloatOperation:
print("refusing to build Decimal from float")
1.1
refusing to build Decimal from float
The Inexact trap raises whenever rounding throws away nonzero digits. Use it to assert that a computation was exact:
from decimal import Decimal, Inexact, localcontext
with localcontext() as ctx:
ctx.traps[Inexact] = True
print(Decimal("10.50") / 2)
try:
Decimal(10) / 3
except Inexact:
print("10 / 3 is not exact")
5.25
10 / 3 is not exact
Mixing Decimal with other types
Decimal combines with int freely. Arithmetic with float raises TypeError, which protects you from silently mixing exact and inexact values:
from decimal import Decimal
d = Decimal("1.5")
print(d + 1)
try:
d + 1.5
except TypeError as e:
print(e)
2.5
unsupported operand type(s) for +: 'decimal.Decimal' and 'float'
Comparisons between Decimal and float are allowed and compare exact values, so Decimal("0.1") == 0.1 is False. Convert explicitly when you need to: float(d), int(d) (truncates toward zero) or Decimal(str(f)).
JSON and databases
The json module can parse numbers straight into Decimal, which avoids a lossy detour through float:
import json
from decimal import Decimal
data = json.loads('{"price": 19.99, "qty": 3}', parse_float=Decimal)
print(data)
print(data["price"] * data["qty"])
print(json.dumps({"price": str(Decimal("19.99"))}))
{'price': Decimal('19.99'), 'qty': 3}
59.97
{"price": "19.99"}
json.dumps doesn't know Decimal; serialize it as a string (or pass default=str). Database drivers usually map SQL NUMERIC/DECIMAL columns to Decimal automatically (psycopg, mysqlclient, SQLAlchemy's Numeric). SQLite has no exact decimal type, so store money as integer cents or text there.
Fractions
fractions.Fraction represents a rational number exactly as a pair of integers. Results are always reduced to lowest terms:
from fractions import Fraction
print(Fraction(1, 3))
print(Fraction(6, 8))
print(Fraction(-4, 6))
print(Fraction(5))
print(Fraction("3/7"))
print(Fraction("1.25"))
print(Fraction(" -2/10 "))
1/3
3/4
-2/3
5
3/7
5/4
-1/5
Arithmetic stays exact, with no rounding at all:
from fractions import Fraction
a = Fraction(1, 3)
b = Fraction(1, 6)
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** 2)
print(sum([Fraction(1, 10)] * 10))
print(Fraction(1, 3) * 3 == 1)
1/2
1/6
1/18
2
1/9
1
True
Access the parts with numerator and denominator, or get both at once with as_integer_ratio():
from fractions import Fraction
f = Fraction(22, 8)
print(f.numerator, f.denominator)
print(f.as_integer_ratio())
print(float(f), int(f))
print(f.is_integer(), Fraction(8, 4).is_integer())
11 4
(11, 4)
2.75 2
False True
Fraction.is_integer() was added in Python 3.12.
Fraction from float and limit_denominator
Like Decimal, a Fraction built from a float captures the float's exact binary value, which looks alarming:
from fractions import Fraction
print(Fraction(0.1))
print(Fraction("0.1"))
print(Fraction(0.1).limit_denominator())
3602879701896397/36028797018963968
1/10
1/10
limit_denominator(max_denominator=1000000) finds the closest fraction whose denominator doesn't exceed the limit. It's also useful for rational approximations:
import math
from fractions import Fraction
pi = Fraction(math.pi)
for limit in (10, 100, 1000, 100000):
approx = pi.limit_denominator(limit)
print(f"{limit:>6}: {approx} error={float(approx) - math.pi:+.2e}")
10: 22/7 error=+1.26e-03
100: 311/99 error=-1.79e-04
1000: 355/113 error=+2.67e-07
100000: 312689/99532 error=+2.91e-11
Mixing Fraction with other types
Fraction combines with int and stays exact. Combining with float gives a float, and Fraction with Decimal is a TypeError:
from decimal import Decimal
from fractions import Fraction
f = Fraction(1, 4)
print(f + 1, type(f + 1).__name__)
print(f + 0.5, type(f + 0.5).__name__)
print(Fraction(Decimal("0.75")))
try:
f + Decimal("0.5")
except TypeError:
print("can't add Fraction and Decimal")
5/4 Fraction
0.75 float
3/4
can't add Fraction and Decimal
Formatting fractions
Since Python 3.12, Fraction supports float-style format specs:
from fractions import Fraction
f = Fraction(2, 3)
print(f"{f}")
print(f"{f:.4f}")
print(f"{f:.1%}")
print(f"{f:>10}")
2/3
0.6667
66.7%
2/3
An exact computation example
Fractions shine when intermediate results must not drift. Here the first 1000 terms of the harmonic series are summed exactly, then compared with a float accumulated in a loop:
from fractions import Fraction
exact = Fraction(0)
approx = 0.0
for k in range(1, 1001):
exact += Fraction(1, k)
approx += 1 / k
print(float(exact))
print(approx)
print(len(str(exact.denominator)), "digits in the denominator")
7.485470860550345
7.485470860550343
433 digits in the denominator
The float result is off in the last digits because each += rounds. (The built-in sum() uses compensated summation for floats since Python 3.12, and math.fsum() is exact-rounded, so both would get closer than a plain loop.)
The denominators grow quickly, though. Exact rational arithmetic on long computations can get slow and use lots of memory, so Fraction is best for small, exactness-critical calculations, not number crunching.
Performance
Since Python 3.3 decimal is implemented in C (libmpdec) and is reasonably fast, but still slower than hardware floats. Fraction is written in pure Python and is much slower:
import timeit
setup = "from decimal import Decimal; from fractions import Fraction"
tests = {
"float": "x = 1.1; y = 2.2; x * y + x / y",
"Decimal": "x = Decimal('1.1'); y = Decimal('2.2'); x * y + x / y",
"Fraction": "x = Fraction(11, 10); y = Fraction(22, 10); x * y + x / y",
}
for name, stmt in tests.items():
t = timeit.timeit(stmt, setup, number=200_000)
print(f"{name:8} {t:.3f}s")
Typical output (your numbers will differ):
float 0.006s
Decimal 0.081s
Fraction 0.326s
For most business code the cost of Decimal is irrelevant compared to I/O. If you need to process millions of money amounts fast, storing integer cents (or using NumPy with integer arrays) is an alternative.
Which type to use
| Need | Use |
|---|---|
| Scientific, statistical, graphics math | float |
| Compare floats approximately | math.isclose(a, b) |
| Money, prices, tax, invoices | Decimal created from strings |
| Round money to cents | d.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) |
| More (or fewer) significant digits | with localcontext(prec=50): |
| Catch accidental floats | ctx.traps[FloatOperation] = True |
| Parse JSON numbers exactly | json.loads(s, parse_float=Decimal) |
| Exact ratios like 1/3 | Fraction(1, 3) |
| Nice fraction from a float | Fraction(x).limit_denominator(1000) |
| Money in a database without a decimal type | integer cents |