float() is a built-in Python function that converts a number or string to a floating-point number — essential for numerical computations, data cleaning, type coercion, and preparing inputs for scientific libraries. In 2026, float() remains a core tool in data science (pandas/Polars type conversion, missing value handling), software engineering (input parsing, configuration), and ML pipelines — handling strings, integers, booleans, and even NaN/inf values with clear error reporting. It’s fast, reliable, and vectorized in NumPy/Dask/Polars for large-scale data processing.
Here’s a complete, practical guide to using float() in Python: basic conversion, string parsing, error handling, real-world patterns (earthquake magnitude parsing, data cleaning), and modern best practices with type hints, performance, edge cases, and integration with NumPy/Dask/Polars/pandas.
Basic float() usage — convert integers, strings, and other types.
print(float(42)) # 42.0
print(float(-3)) # -3.0
print(float("3.14")) # 3.14
print(float("42")) # 42.0
print(float(True)) # 1.0
print(float(False)) # 0.0
print(float("inf")) # inf
print(float("-inf")) # -inf
print(float("nan")) # nan
Error handling & safe conversion — catch ValueError for invalid inputs.
def safe_float(value, default: float = 0.0) -> float:
"""Convert to float safely with default fallback."""
try:
return float(value)
except (ValueError, TypeError):
return default
# Usage examples
print(safe_float("3.14")) # 3.14
print(safe_float("invalid", 0.0)) # 0.0
print(safe_float(None)) # 0.0
Real-world pattern: parsing earthquake magnitudes from mixed data sources.
import pandas as pd
import numpy as np
# Sample messy DataFrame
df = pd.DataFrame({
'mag_str': ['7.2', '6.8', 'invalid', '5.9', 'nan', '8.0']
})
# Safe conversion column
df['mag'] = df['mag_str'].apply(safe_float)
# Alternative: vectorized with pd.to_numeric
df['mag_pd'] = pd.to_numeric(df['mag_str'], errors='coerce')
# NumPy version
df['mag_np'] = np.where(
df['mag_str'].str.match(r'^-?\d*\.?\d+$|^nan$|^inf$|^-inf$'),
df['mag_str'].astype(float),
np.nan
)
print(df)
# Clean magnitudes: 7.2, 6.8, nan, 5.9, nan, 8.0
Best practices for float() in Python & data workflows. Use float() for explicit conversion — when you need a float result. Modern tip: prefer Polars pl.col('mag_str').cast(pl.Float64) — fast & handles errors gracefully; Dask for distributed data. Use pd.to_numeric(errors='coerce') — pandas standard for safe column conversion. Add type hints — def parse_float(s: str) -> float | None. Handle NaN/inf — float('nan'), float('inf'). Use try/except — for user input or messy data. Use np.nan — as default for invalid values in numeric pipelines. Avoid float() in tight loops — vectorize with NumPy/Polars. Use float.hex() — for precise representation. Use decimal.Decimal — for exact decimal arithmetic. Profile performance — float() is fast; avoid unnecessary conversions. Use float.fromhex() — for hex string conversion. Use math.isfinite() — check for inf/nan. Use math.isnan() — detect NaN. Use math.isclose() — compare floats safely. Use float.as_integer_ratio() — exact fraction representation.
float() converts numbers/strings to floating-point — handles integers, decimals, scientific notation, nan/inf, and enables safe numeric processing. In 2026, use with pd.to_numeric/Polars casting for data cleaning, NumPy/Dask for vectorization, and safe wrappers for user input. Master float(), and you’ll handle numerical type conversion cleanly and efficiently in any Python workflow.
Next time you need a floating-point number — use float(). It’s Python’s cleanest way to say: “Turn this into a decimal — safely and reliably.”