Python’s float is fast, but it stores numbers in binary, so most decimal fractions such as 0.1 are only stored approximately. That is why 0.1 + 0.2 prints 0.30000000000000004. For money, bills and anything that must match a calculator exactly, use the decimal module. For exact fractions such as one third, use the fractions module. Both are built in.
In this lesson you will learn
- Why floats give slightly wrong answers
- Creating
Decimalvalues the right way - Rounding money with
quantizeandROUND_HALF_UP - Exact fractions with
Fraction - Choosing between float, Decimal and Fraction
You should know numbers in Python and string formatting.
Decimal for Money
from decimal import Decimal, ROUND_HALF_UP, getcontext
# float cannot store most decimal fractions exactly
print("float: ", 0.1 + 0.2, "| equal to 0.3?", 0.1 + 0.2 == 0.3)
print("Decimal:", Decimal("0.1") + Decimal("0.2"), "| equal?", Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
# Always build Decimals from strings, not floats
print("from float: ", Decimal(0.1))
print("from string:", Decimal("0.1"))
# A shopping bill with 7.5% VAT, rounded to paisa
items = [("Tea 400g", "245.50"), ("Sugar 1kg", "135.00"), ("Biscuit", "42.75")]
subtotal = sum(Decimal(price) for _, price in items)
vat = (subtotal * Decimal("0.075")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(f"subtotal {subtotal} VAT {vat} total {subtotal + vat}")
# round() on floats uses banker's rounding and float error; quantize is explicit
print("round(2.675, 2) =", round(2.675, 2))
print("Decimal quantize =", Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
# Precision for division is set in the context (default 28 digits)
getcontext().prec = 6
print("1/7 with 6 digits:", Decimal(1) / Decimal(7))
Output
float: 0.30000000000000004 | equal to 0.3? False
Decimal: 0.3 | equal? True
from float: 0.1000000000000000055511151231257827021181583404541015625
from string: 0.1
subtotal 423.25 VAT 31.74 total 454.99
round(2.675, 2) = 2.67
Decimal quantize = 2.68
1/7 with 6 digits: 0.142857
- A float stores 0.1 as the nearest binary number, which is very slightly more than 0.1. The tiny errors add up, so
0.1 + 0.2 == 0.3isFalse.Decimalstores the decimal digits themselves, so the same sum is exact. - Create Decimals from strings.
Decimal(0.1)copies the float’s error exactly, giving that long number;Decimal("0.1")is exactly one tenth. - The bill adds prices as Decimals and works out 7.5% VAT.
quantize(Decimal("0.01"))rounds to two decimal places, that is, to the paisa, andROUND_HALF_UProunds halves upwards as people do by hand. round(2.675, 2)gives 2.67, not 2.68, because the float 2.675 is really 2.67499999… Decimal with an explicit rounding rule gives the expected 2.68.getcontext().precsets how many significant digits division keeps. The default of 28 is plenty for money.
Fraction for Exact Ratios
from fractions import Fraction
from decimal import Decimal
half = Fraction(1, 2)
third = Fraction(1, 3)
print(half, "+", third, "=", half + third)
print("from text:", Fraction("3/4"), "| from decimal text:", Fraction("0.125"))
print("simplified automatically:", Fraction(6, 8))
# Sharing a 1,000 taka prize exactly
shares = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 6)]
print("shares add to", sum(shares))
for s in shares:
print(f" {s} of 1000 = {1000 * s} = {float(1000 * s):.2f} taka")
# Exact answers where floats drift
exact, approx = Fraction(0), 0.0
for _ in range(10):
exact += Fraction(1, 10)
approx += 0.1
print("ten tenths as Fraction:", exact, "| as float:", approx)
# Find a simple fraction near a float
print("pi approx:", Fraction(3.14159265).limit_denominator(10), Fraction(3.14159265).limit_denominator(1000))
print("numerator/denominator:", Fraction(9, 12).numerator, Fraction(9, 12).denominator)
print("convert:", float(Fraction(7, 8)), Decimal(7) / Decimal(8))
Output
1/2 + 1/3 = 5/6
from text: 3/4 | from decimal text: 1/8
simplified automatically: 3/4
shares add to 1
1/2 of 1000 = 500 = 500.00 taka
1/3 of 1000 = 1000/3 = 333.33 taka
1/6 of 1000 = 500/3 = 166.67 taka
ten tenths as Fraction: 1 | as float: 0.9999999999999999
pi approx: 22/7 355/113
numerator/denominator: 3 4
convert: 0.875 0.875
Fraction(1, 2) + Fraction(1, 3)gives exactly5/6. Fractions are always stored in lowest terms, soFraction(6, 8)becomes3/4.- A prize shared as one half, one third and one sixth adds up to exactly 1, so nothing is lost or created. Each share is converted to a float only at the end, for display.
- Adding 0.1 ten times as a float gives 0.9999999999999999, while ten
Fraction(1, 10)values give exactly 1. limit_denominatorfinds the closest simple fraction to a number, giving the well-known approximations 22/7 and 355/113 for pi.numeratoranddenominatorgive the two parts, andfloat()converts back when you need it.
float, Decimal or Fraction?
| Type | Exact? | Speed | Use for |
|---|---|---|---|
float | No (binary approximation) | Fastest | Science, measurements, graphics, machine learning |
Decimal | Yes, for decimal digits | Slower | Money, prices, tax, invoices |
Fraction | Yes, for any ratio | Slowest | Maths teaching, ratios, exact sharing |
Common Mistakes
- Writing
Decimal(19.99)instead ofDecimal("19.99"), which carries the float error into your Decimal. - Mixing Decimal and float in one calculation, which raises
TypeError. Convert everything to Decimal first. - Comparing floats with
==. Usemath.isclose(a, b)for floats. - Rounding only at the end when the rules say each line must be rounded. Follow the rule your bill or tax office uses.
Practice Exercises
Exercise 1. Split a 1,000 taka bill equally among 3 friends, rounding each share to the paisa, and show how much is left over.
Show answer
from decimal import Decimal, ROUND_DOWN
total = Decimal("1000")
share = (total / 3).quantize(Decimal("0.01"), rounding=ROUND_DOWN)
print(share, total - share * 3) # 333.33 0.01
Exercise 2. Add 1/4, 2/5 and 3/10 exactly and print the answer as a fraction and as a percentage.
Show answer
from fractions import Fraction
total = Fraction(1, 4) + Fraction(2, 5) + Fraction(3, 10)
print(total, f"{float(total):.0%}") # 19/20 95%
Frequently Asked Questions
Can I store money as whole paisa instead?
Yes. Keeping amounts as integers in the smallest unit (paisa or cents) is exact and fast, and many databases and payment systems do this. Convert to taka only for display.
What is banker’s rounding?
Rounding halves to the nearest even digit, so 2.5 becomes 2 and 3.5 becomes 4. Python’s round() uses it, and it is the default for Decimal too, because it avoids a bias upwards over many roundings. Choose ROUND_HALF_UP when you need the school-book rule.
Summary
- Floats are binary approximations; small errors are normal.
- Use
Decimal, created from strings, for money, and round withquantize. - Use
Fractionfor exact ratios such as 1/3. - Never mix Decimal and float in one calculation.
