Edexcel International Advanced Level Computer Science, point 18.1.1
Floating-point numbers are approximate (11.3.1): many decimal fractions can't be stored exactly. This page covers the methods Python offers to handle them correctly. Check the Programming Language Subset (PLS) for the exact functions allowed.
The problem
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(1.1 * 3) # 3.3000000000000003
Errors can build up in long calculations, and are unacceptable in money or exact decimal values.
a. The decimal module and c. the Decimal class
The decimal module provides the Decimal class, which stores numbers as exact decimal digits (not binary fractions), so 0.1 is exactly 0.1.
from decimal import Decimal
a = Decimal("0.1")
b = Decimal("0.2")
print(a + b) # 0.3
print(a + b == Decimal("0.3")) # True
print(Decimal("19.99") * 3) # 59.97
Rules:
- Create a
Decimalfrom a string (Decimal("0.1")), not from a float:Decimal(0.1)copies the float's error (0.1000000000000000055511...). Decimalmixes withintbut not withfloat(aTypeError): convert deliberately.- Arithmetic:
+,-,*,/,//,%,**all work.
Precision and context
from decimal import Decimal, getcontext
getcontext().prec = 6 # 6 significant digits
print(Decimal(1) / Decimal(7)) # 0.142857
b. Rounding
Rounding floats
print(round(3.14159, 2)) # 3.14
# 2 4 (halves go to the even number)
print(round(2.5), round(3.5))
Rounding Decimals with quantize
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("2.675")
print(price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) # 2.68
# 2.67 (the float is really 2.67499...)
print(round(2.675, 2))
quantize(Decimal("0.01"))rounds to 2 decimal places.ROUND_HALF_UPis the "school" rule (0.5 rounds up). The default (ROUND_HALF_EVEN) rounds halves to the nearest even digit.- For display only, use formatting:
f"{value:.2f}"(the stored value isn't changed).
d. Data type conversions
from decimal import Decimal
print(float("3.5"), int("42"), str(2.50)) # 3.5 42 2.5
print(int(3.9), int(-3.9)) # 3 -3 (truncates)
print(float(Decimal("0.1"))) # 0.1 (back to a float)
print(Decimal(str(0.1))) # 0.1 (via a string)
print(Decimal(3) + 1) # 4 (an int is fine)
Convert as soon as input arrives, work in one type, and convert only for output or when another function needs it.
e. Exception handling
Conversions and arithmetic can fail (7.1.1):
from decimal import Decimal, InvalidOperation
def read_money(text):
try:
value = Decimal(text)
except InvalidOperation: # not a valid number
return None
if value < 0:
return None
return value.quantize(Decimal("0.01"))
print(read_money("12.5")) # 12.50
print(read_money("abc")) # None
| Error | Cause |
|---|---|
ValueError |
float("abc"), int("3.5") |
decimal.InvalidOperation |
Decimal("abc") |
ZeroDivisionError |
Division by zero (also for Decimal) |
OverflowError |
A float too large for the range |
TypeError |
Decimal + float |
f. Comparing floating-point numbers
Never test floats with ==. Compare using a small tolerance:
import math
a = 0.1 + 0.2
print(a == 0.3) # False
print(abs(a - 0.3) < 1e-9) # True: within a tolerance
print(math.isclose(a, 0.3)) # True: a built-in check
math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)checks relative closeness. Useabs_tolwhen comparing with zero.Decimalvalues compare exactly:Decimal("0.1") + Decimal("0.2") == Decimal("0.3")isTrue.- Integers (pence) are the simplest way to compare money.
Choosing a method
| Situation | Method |
|---|---|
| Scientific measurement, approximate is fine | float, rounded for display |
| Money and exact decimals | Decimal (or integer pence) |
| Checking two floats are equal | math.isclose or a tolerance |
| Display to 2 decimal places | f"{x:.2f}" |
| Round a stored value | round() or quantize() |
| User input | Convert inside try/except |
Worked example
Task: a restaurant adds a 12.5% service charge to prices entered as text, and totals the bill exactly, rounded to the nearest penny (halves rounding up).
from decimal import Decimal, ROUND_HALF_UP, InvalidOperation
SERVICE = Decimal("0.125")
PENNY = Decimal("0.01")
def with_service(text):
try:
price = Decimal(text)
except InvalidOperation:
return None
return (price * (1 + SERVICE)).quantize(PENNY, rounding=ROUND_HALF_UP)
prices = ["19.99", "4.50", "abc", "0.10"]
total = Decimal("0.00")
for p in prices:
result = with_service(p)
if result is None:
print(f"Skipping {p!r}")
else:
total += result
print(total) # 27.66
Check by hand: , which rounds to . , which rounds to . , which rounds to . The total is . ✓ The text "abc" is skipped with a message.
Why Decimal? Decimal built from strings is exact, so long totals don't drift, and quantize gives a controlled, stated rounding rule.
Exam tip: create Decimal from strings, never use == on floats (use isclose or a tolerance), and round with a stated rule when money is involved. Handle conversion errors with try/except.
Check yourself
Why is 0.1 + 0.2 == 0.3 False in Python?
Floats store binary approximations, so 0.1 + 0.2 is 0.30000000000000004, not exactly 0.3.
How should you create a Decimal for 0.1?
From a string: Decimal("0.1"), not Decimal(0.1), which copies the float's error.
How can you safely compare two floats?
Check that their difference is within a small tolerance, for example with math.isclose.
What does quantize do?
It rounds a Decimal to a given number of decimal places using a chosen rounding rule.