Topic 28 of 64
Integer & Float
Overview
Python integers are arbitrary precision (no overflow), while floats use IEEE 754 double precision. Knowing the quirks of float arithmetic prevents numeric bugs in financial and scientific applications.
Syntax
python
# Integers — unlimited precision
big = 10 ** 100 # googol — no overflow!
# Floats
x = 3.14
y = 1.5e10 # scientific notation
# Division operators
7 / 2 # 3.5 (true division — always float)
7 // 2 # 3 (floor division)
7 % 2 # 1 (modulo)
# Float precision issue
0.1 + 0.2 == 0.3 # False!Common Pitfalls
- Never use floats for money — always use the Decimal module or store amounts as integer cents.
- 0.1 + 0.2 = 0.30000000000000004 in Python — use round() or math.isclose() for float comparisons.
- Interview tip: Python 3 division always returns float (7/2 = 3.5). Use // for integer floor division.
Real-World Example
Using Decimal for accurate financial calculations
example
python
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("19.99")
tax = Decimal("0.085")
total = price * (1 + tax)
rounded = total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(rounded) # 21.69