Python Floating Point Numbers (Floats)

What is a Float?

In Python, a float is a data type used to represent real numbers that have a decimal point.

Examples: 3.14, -0.001, 2.0, 0.0, 5e-3 (scientific notation).

Creating Float Values

# Examples of float literals
a = 3.14
b = -2.5
c = 0.0
d = 5e-3    # 5 × 10⁻³ = 0.005
print(a, b, c, d)

Operations with Floats

x = 5.5
y = 2.0

print(x + y)  # Addition, output: 7.5
print(x - y)  # Subtraction, output: 3.5
print(x * y)  # Multiplication, output: 11.0
print(x / y)  # Division, output: 2.75

Mixing Integers and Floats

When integers and floats are used together in operations, Python converts integers to floats automatically.

i = 7      # int
f = 2.5    # float

result = i + f
print(result)       # Output: 9.5 (float)
print(type(result)) # <class 'float'>

Precision and Floating Point Errors

Floats are represented in binary and sometimes lead to precision issues.

print(0.1 + 0.2)  # Output: 0.30000000000000004

This is a common floating point arithmetic artifact and is not a bug in Python.

Rounding Floats

num = 3.14159
print(round(num, 2))  # Output: 3.14 (round to 2 decimal places)
print(round(num))     # Output: 3 (round to nearest integer)

Converting to Float

print(float(5))       # 5.0
print(float("3.14"))  # 3.14 (from string)
print(float("2e3"))   # 2000.0 (scientific notation string)

Best Practices