The float() function is one of Python’s most frequently used built-ins — it converts strings, integers, or other numbers into floating-point values (numbers with decimal points). It’s essential when reading user input, parsing files (CSV, JSON, config), or preparing numeric data for math operations. In 2026, float() remains simple yet powerful, but understanding its behavior, edge cases, and error handling is key to writing robust code.
Here’s a complete, practical guide to using float(): basic conversions, real-world patterns, common gotchas, and modern best practices with type hints and error handling.
At its core, float() takes one argument and returns a float. It works on strings that look like numbers, integers (adding .0), or existing floats (no change).
# From string
print(float("3.14")) # 3.14
print(float("42")) # 42.0
print(float("-0.5")) # -0.5
# From integer
print(float(5)) # 5.0
# From float (no-op)
print(float(3.14159)) # 3.14159
Real-world use: parsing input from users, files, APIs, or databases — where data often arrives as strings.
# User input (common pattern)
user_input = input("Enter temperature in Celsius: ") # returns string
try:
temp_c = float(user_input)
temp_f = temp_c * 9/5 + 32
print(f"{temp_c}°C = {temp_f:.1f}°F")
except ValueError:
print("Invalid input — please enter a number")
Another everyday pattern: reading numeric columns from CSV/JSON/config files — always expect strings.
import csv
with open("sales.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
try:
price = float(row["price"])
quantity = float(row["quantity"])
total = price * quantity
print(f"Total: {total:.2f}")
except (ValueError, KeyError) as e:
print(f"Bad row: {row} ? {e}")
Advanced cases: scientific notation, leading/trailing whitespace, and special floats.
print(float("1.23e-4")) # 0.000123 (scientific notation)
print(float(" 42.0 ")) # 42.0 (strips whitespace)
print(float("inf")) # inf
print(float("-inf")) # -inf
print(float("nan")) # nan
Best practices make float() safe and reliable. Always wrap in try/except ValueError — invalid strings crash otherwise. Prefer explicit conversion over implicit — don’t rely on int("3.0") failing silently. Use type hints (float) in function signatures — improves readability and IDE support. For large-scale parsing, consider pd.to_numeric(errors='coerce') (pandas) or pl.col("col").cast(pl.Float64, strict=False) (Polars) — they handle errors gracefully. Pitfalls include assuming all inputs are clean — user input, CSV, APIs often contain junk. Another common mistake: float("3,14") fails (comma separator) — clean strings first or use locale.atof(). Modern tip: use decimal.Decimal instead of float for money/finance — avoids floating-point precision errors.
The float() function is simple but essential — it bridges strings and real numeric work. In 2026, use it with error handling, type hints, and clean input preparation. Master it, and you’ll handle user input, files, APIs, and data pipelines with confidence and robustness.
Next time you see a string that should be a number — convert it with float() inside a try. It’s the safest, most Pythonic way to move from text to math.