Python - Numbers & Casting

Overview

Estimated time: 25–35 minutes

Work with numeric types and safely convert between types.

Learning Objectives

  • Use int and float; know Decimal and Fraction for precision.
  • Cast values with int(), float(), and str() appropriately.
  • Understand floating point pitfalls and when to prefer Decimal.

Prerequisites

Integers and floats

x = 7
y = 2
print(x / y)   # float division -> 3.5
print(x // y)  # floor division -> 3
print(x % y)   # modulo -> 1
print(2 ** 10) # exponentiation -> 1024

Casting

print(int("42"))      # 42
print(float("3.14"))  # 3.14
print(str(123))        # '123'

Precision with Decimal and Fraction

from decimal import Decimal, getcontext
from fractions import Fraction

print(0.1 + 0.2)                # 0.30000000000000004
print(Decimal("0.1") + Decimal("0.2"))  # 0.3
print(Fraction(1, 3) + Fraction(1, 6))   # 1/2

getcontext().prec = 4
print(Decimal(1) / Decimal(7))  # 0.1429 (with precision 4)

Common Pitfalls

  • Comparing floats directly; use a tolerance or math.isclose.
  • Constructing Decimal from a float; prefer string input to avoid binary rounding issues.

Checks for Understanding

  1. What’s the difference between / and //?
  2. Why use Decimal("0.1") instead of Decimal(0.1)?
Show answers
  1. / is true division (float), // is floor division.
  2. To avoid inheriting binary floating point rounding errors.

Exercises

  1. Compute monthly interest on a balance using Decimal to two decimal places.
  2. Sum 1/10 ten times using Fraction and compare to float.