Numbers: int, float, Decimal & Fraction
Published by Brayan K
Python offers four numeric types for different jobs: int for exact whole numbers of any size, float for fast approximate decimals, Decimal for exact base-10 math like money, and Fraction for exact rational numbers with no rounding at all.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Choose a representation before the calculation
A ticket count, a measured temperature and a share of a recipe are different kinds of quantity. An integer represents whole units exactly, subject to available memory. A float approximates many decimal fractions. Decimal preserves decimal input and has configurable arithmetic precision. Fraction stores an exact ratio of integers. None of these choices makes an unspecified rounding policy disappear.
from decimal import Decimal
from fractions import Fraction
print(0.1 + 0.2 == 0.3)
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
print(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10))
print(10 ** 25 + 1 - 10 ** 25)
# ✅ Expected output:
# False
# True
# True
# 1The last expression stays entirely in integers. Converting an exact value to a float can lose information before later arithmetic runs. For basic operators and the difference between division and floor division, use Operators and Expressions. This lesson concentrates on representation and rounding decisions.
value = 2 ** 53 + 1
converted = float(value)
print(int(converted) == value)
print(value - int(converted))
# ✅ Expected output:
# False
# 1Formatting a float does not change its stored value
from math import isclose
total = 0.1 + 0.2
print(f"Display: {total:.2f}")
print("Exact equality:", total == 0.3)
print("Close:", isclose(total, 0.3))
print("Near zero, default:", isclose(1e-12, 0.0))
print("Near zero, chosen tolerance:", isclose(1e-12, 0.0, abs_tol=1e-9))
# ✅ Expected output:
# Display: 0.30
# Exact equality: False
# Close: True
# Near zero, default: False
# Near zero, chosen tolerance: TrueThe formatted string is a presentation choice; total still holds the original float. isclose compares with relative and absolute tolerances. Near zero, a chosen positive absolute tolerance is often necessary. Pick tolerances from the meaning and units of your data; a default cannot decide how much measurement error your application accepts.
Floats are appropriate for many measurements and numerical calculations. The lesson is not to replace all floats with Decimal, but to stop demanding exact decimal identities from a binary representation. Formatting and interpolation themselves belong to f-strings & String Formatting.
Construct decimal quantities from their decimal input
from decimal import Decimal
from_text = Decimal("0.1")
from_float = Decimal(0.1)
print("From text:", from_text)
print("Equal:", from_text == from_float)
print("Float conversion:", from_float)
# ✅ Expected output:
# From text: 0.1
# Equal: False
# Float conversion: 0.1000000000000000055511151231257827021181583404541015625The constructor does not know that a float originally came from the characters 0.1. It converts the float value it actually receives. For user-supplied decimal quantities, parse their original strings before doing arithmetic. Converting an already rounded calculation through str later cannot recover precision that was lost earlier.
from decimal import Decimal
print(Decimal("1.20") + 0.3)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'Make both operands part of the intended numeric model. Decimal can combine with integers, but ordinary arithmetic with a float is rejected. Converting everything to float to silence the exception would abandon the decimal calculation you selected.
Decimal precision and rounding are explicit decisions
from decimal import Decimal, localcontext
with localcontext() as context:
context.prec = 4
amount = Decimal("123.456")
print("Constructed:", amount)
print("After arithmetic:", amount + Decimal("0"))
print("One third:", Decimal(1) / Decimal(3))
# ✅ Expected output:
# Constructed: 123.456
# After arithmetic: 123.5
# One third: 0.3333Decimal is not unlimited exact arithmetic. A finite precision rounds sufficiently long arithmetic results, including repeating fractions. A local context contains this temporary choice so the surrounding program does not inherit it. Base-ten exactness applies to representable decimal values; calculation precision still matters.
from decimal import Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP
value = Decimal("2.345")
unit = Decimal("0.01")
print("Half even:", value.quantize(unit, rounding=ROUND_HALF_EVEN))
print("Half up:", value.quantize(unit, rounding=ROUND_HALF_UP))
# ✅ Expected output:
# Half even: 2.34
# Half up: 2.35quantize matches the exponent of the supplied unit. The two rules disagree at this tie, so “round to two places” is not a complete specification. These are programming examples, not a universal billing rule. A real application must establish when rounding happens and which policy it follows.
Keep exact ratios without converting through float
from fractions import Fraction
share = Fraction(1, 3) + Fraction(1, 6)
print(share)
print(share.numerator, share.denominator)
print(Fraction("0.1") == Fraction(1, 10))
print(Fraction(0.1) == Fraction(1, 10))
print(Fraction(0.333333).limit_denominator(10))
# ✅ Expected output:
# 1/2
# 1 2
# True
# False
# 1/3Fractions reduce automatically. A string decimal can describe an exact rational value; a float constructor preserves the float’s actual ratio. limit_denominator chooses an approximation with a bounded denominator. It is useful when an approximation is intended, but it does not prove which fraction produced the input.
from fractions import Fraction
Fraction(3, 0)
# ✅ Expected error:
# ZeroDivisionError: Fraction(3, 0)Complete an explicit decimal calculation
Multiply a string price by an integer quantity, then round once with a named rule. Fill the original decimal input, the output unit and the rounding constant. Keep the calculation in Decimal throughout.
from decimal import Decimal, ROUND_HALF_UP
price = Decimal(___)
total = price * 3
rounded = total.quantize(Decimal(___), rounding=___)
print(rounded)
# 👉 replace ___ with "1.235"
# 👉 replace ___ with "0.01"
# 👉 replace ___ with ROUND_HALF_UP
# ✅ Expected output:
# 3.71Compare rounding each line with rounding the total
Two lines each cost the decimal amount 0.335. Compute one total by rounding each line to two places with ROUND_HALF_UP and then adding. Compute another by adding the unrounded lines and rounding only once. Print both totals and their difference. The task is to expose the policy difference, not to declare either policy universally correct.
from decimal import Decimal, ROUND_HALF_UP
lines = [Decimal("0.335"), Decimal("0.335")]
unit = Decimal("0.01")
by_line = sum((line.quantize(unit, rounding=ROUND_HALF_UP) for line in lines), Decimal(0))
at_end = sum(lines, Decimal(0)).quantize(unit, rounding=ROUND_HALF_UP)
print("Round each line:", by_line)
print("Round at end:", at_end)
print("Difference:", by_line - at_end)
# ✅ Expected output:
# Round each line: 0.68
# Round at end: 0.67
# Difference: 0.01Both totals come from the same input values and the same rounding mode. Moving the rounding boundary changes the result. Write that boundary into the requirements and tests, especially when another system must reproduce the calculation.
Practice quiz
What does this program print? from decimal import Decimal print(Decimal("0.1") == Decimal(0.1))
- True
- False
- 0.1
- TypeError
Answer: False. A float conversion preserves the binary approximation, not the original decimal spelling.
What does this program print? n = 2 ** 53 + 1 print(n - int(float(n)))
- 0
- -1
- 2
- 1
Answer: 1. This float cannot retain that exact integer unit.
What does this program print? from math import isclose print(isclose(1e-12, 0.0)) print(isclose(1e-12, 0.0, abs_tol=1e-9))
- False True
- True True
- False False
- True False
Answer: False True. The explicit positive absolute tolerance covers this near-zero difference.
What does this program print? from decimal import Decimal, localcontext with localcontext() as ctx: ctx.prec = 3 x = Decimal("12.345") print(x) print(x + Decimal(0))
- 12.3 12.3
- 12.345 12.345
- 12.345 12.3
- 12.345 12.35
Answer: 12.345 12.3. Construction retains the input digits; arithmetic applies the context precision.
What does this program print? from decimal import Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP x = Decimal("2.345") unit = Decimal("0.01") print(x.quantize(unit, rounding=ROUND_HALF_EVEN)) print(x.quantize(unit, rounding=ROUND_HALF_UP))
- 2.35 2.35
- 2.34 2.34
- 2.35 2.34
- 2.34 2.35
Answer: 2.34 2.35. The tie goes to an even final digit under half-even and away from zero under half-up.
What does this program print? from fractions import Fraction print(Fraction(1, 3) + Fraction(1, 6))
- 1/2
- 0.5
- 2/9
- 3/6
Answer: 1/2. The exact rational sum is automatically reduced.
What does this program print? from fractions import Fraction print(Fraction("0.1") == Fraction(1, 10)) print(Fraction(0.1) == Fraction(1, 10))
- True True
- False True
- True False
- False False
Answer: True False. The string and integer ratio are exact; the float carries its approximation.
Which requirement is still missing from “round decimal amounts to two places”?
- Which Python editor to use
- The rounding rule and when to apply it
- Whether to print the source code
- The variable name
Answer: The rounding rule and when to apply it. Both tie handling and the stage of rounding can affect the answer.
Continue this course
- Previous: Binary Search with bisect
- Next: Strings, Bytes & Unicode Encodings — str vs bytes, encode/decode, UTF-8, and fixing UnicodeDecodeError
- Quick reference: Python cheat sheet