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).
# 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)
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
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'>
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.
num = 3.14159
print(round(num, 2)) # Output: 3.14 (round to 2 decimal places)
print(round(num)) # Output: 3 (round to nearest integer)
print(float(5)) # 5.0
print(float("3.14")) # 3.14 (from string)
print(float("2e3")) # 2000.0 (scientific notation string)
decimal
module for financial calculations.round()
when you need to display a fixed number of decimal places.