Python floats represent numbers with a fractional part, such as 3.14, -0.5, and 1250.00. They are essential for measurements, averages, percentages, scientific calculations, prices, and many other programs.
Floats look simple, but computers store most decimal values as binary approximations. Understanding that limitation helps you avoid surprising results and choose the correct numeric type for each task.
What is a float in Python?
A float is Python’s built-in floating-point number type:
temperature = 21.5
height = 1.82
discount = 0.15
print(type(temperature)) # <class 'float'>
A number written with a decimal point becomes a float. Scientific notation also creates floats:
large = 1.2e6
small = 4.5e-4
print(large) # 1200000.0
print(small) # 0.00045
For a broader comparison of numeric and collection types, review the guide to Python data types.
Creating and converting floats
Use float() to convert compatible strings or integers:
price = float("19.90")
average = float(8)
print(price)
print(average)
Invalid text raises ValueError:
try:
value = float(input("Enter a decimal number: "))
except ValueError:
print("That is not a valid number.")
The guides to Python input() and exception handling explain robust user validation.
Arithmetic with floats
Floats support the standard arithmetic operators:
a = 10.5
b = 2.0
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** b)
print(a % b)
When an operation combines an integer and a float, Python generally returns a float:
result = 5 + 2.5
print(result) # 7.5
print(type(result)) # float
Regular division with / always returns a float, even when the result is mathematically whole:
print(10 / 2) # 5.0
Floor division with // rounds the quotient toward negative infinity:
print(10.0 // 3) # 3.0
print(-10.0 // 3) # -4.0
Why 0.1 + 0.2 is not exactly 0.3
print(0.1 + 0.2)
# 0.30000000000000004
This is not a Python bug. Most decimal fractions cannot be represented exactly as finite binary fractions. Python stores the nearest available floating-point value.
The official floating-point arithmetic tutorial explains this representation issue and why printing fewer digits can hide, but not remove, the approximation.
Comparing floats correctly
Direct equality can fail after calculations:
total = 0.1 + 0.2
print(total == 0.3) # False
Use math.isclose() when approximate equality is acceptable:
import math
total = 0.1 + 0.2
print(math.isclose(total, 0.3))
You can set relative and absolute tolerances:
math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)
An absolute tolerance is especially important when comparing values near zero.
Rounding floats
round() returns a rounded value:
value = 12.34567
print(round(value))
print(round(value, 2))
Python uses “round half to even” in ties. Because the stored float may already be slightly above or below the decimal you typed, some results can look unexpected.
print(round(2.5)) # 2
print(round(3.5)) # 4
Rounding a value for display is different from changing the underlying calculation. F-strings format output without necessarily altering the variable:
price = 19.9876
print(f"${price:.2f}")
See the tutorial on formatting numbers and currency for percentages, alignment, and separators.
When not to use float for money
Small approximations can accumulate in accounting or financial systems. For exact decimal arithmetic, use decimal.Decimal and construct values from strings:
from decimal import Decimal
price = Decimal("19.90")
quantity = Decimal("3")
total = price * quantity
print(total) # 59.70
Avoid creating Decimal values from floats when exact decimal input matters:
# Better
value = Decimal("0.1")
# Carries the float approximation
value_from_float = Decimal(0.1)
The official decimal module documentation describes precision, rounding modes, and contexts.
Special float values
Floats can represent infinity and “not a number”:
positive_infinity = float("inf")
negative_infinity = float("-inf")
not_a_number = float("nan")
Use functions from math to check them:
import math
print(math.isinf(positive_infinity))
print(math.isnan(not_a_number))
print(math.isfinite(12.5))
NaN has unusual comparison behavior:
nan = float("nan")
print(nan == nan) # False
Always use math.isnan() rather than equality to detect NaN.
Useful functions from math
import math
value = 7.8
print(math.floor(value))
print(math.ceil(value))
print(math.trunc(value))
print(math.sqrt(81.0))
print(math.fsum([0.1, 0.1, 0.1]))
math.fsum() provides a more accurate sum for sequences of floats than a basic repeated addition in many cases. The guide to the Python math module covers trigonometry, logarithms, constants, and number theory functions.
Formatting floats for users
distance = 12345.6789
ratio = 0.4236
print(f"Distance: {distance:,.2f} km")
print(f"Completion: {ratio:.1%}")
print(f"Scientific: {distance:.3e}")
Formatting should match the domain. A measurement may need three decimal places, while a percentage may need one. Do not assume two decimals are correct for every value.
Practical example: grade calculator
def read_grade(prompt):
while True:
try:
grade = float(input(prompt))
except ValueError:
print("Enter a numeric grade.")
continue
if not 0 <= grade <= 100:
print("Grade must be between 0 and 100.")
continue
return grade
grades = [
read_grade("First grade: "),
read_grade("Second grade: "),
read_grade("Third grade: "),
]
average = sum(grades) / len(grades)
print(f"Average: {average:.2f}")
This program combines float conversion, validation, lists, functions, and formatted output. The guide to Python functions explains how reusable input helpers improve program structure.
Practical example: measurement conversion
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
def kilometers_to_miles(kilometers):
return kilometers * 0.621371
celsius = 24.5
kilometers = 10.0
print(f"{celsius:.1f} °C = {celsius_to_fahrenheit(celsius):.1f} °F")
print(f"{kilometers:.1f} km = {kilometers_to_miles(kilometers):.2f} miles")
Converting between int and float
int() truncates toward zero; it does not round:
print(int(9.9)) # 9
print(int(-9.9)) # -9
Use round(), math.floor(), or math.ceil() when their specific behavior is intended. The dedicated guide to Python integers covers division, bases, large numbers, and integer methods.
Common mistakes
- Comparing calculated floats with
==. - Using float for exact currency calculations.
- Assuming
int()rounds a number. - Rounding intermediate results too early.
- Ignoring NaN and infinity in imported data.
- Using a comma as the decimal separator in source code.
- Failing to validate text before calling
float().
Best practices
Use floats for scientific, statistical, graphical, and measurement calculations where a small approximation is acceptable. Compare results with tolerances, format only at the presentation layer, and use Decimal or integer minor units for exact financial values.
When processing collections of numerical data, NumPy can perform fast vectorized operations. The NumPy introduction is the natural next step.
Conclusion
Python floats make decimal and scientific calculations convenient, but they are binary approximations. Learn conversion, arithmetic, formatting, math.isclose(), special values, and the difference between display rounding and exact decimal arithmetic.
Choosing between float, Decimal, and integer representations is not about one type being universally better. It is about matching the numeric model to the accuracy requirements of the problem.






