float()
The float type constructor — parse strings into floats, or convert numeric types.
Common call
float(user_input)
Returns
a float — always double precision
Replaces
safer than eval() for numeric parsing
Watch out
"inf" and "nan" both parse silently; empty string raises ValueError
float(xx — A string to parse, or a number to convert. No argument returns 0.0. Objects implementing __float__ are also accepted.type: str | number · default: 0.0=0.0)
→ float
Demo
Live evaluation
Try:
Inputs
xstrstring or number
Output
float('3.14')
3.14
float() parses a string into an IEEE 754 double. Leading and trailing whitespace is stripped. Sign, decimal point, and scientific notation are all supported. Underscore separators (like 1_000_000.5) are allowed since Python 3.6. The special strings "inf", "infinity", and "nan" are recognized case-insensitively — a silent gotcha when parsing untrusted input.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| x | str | number | no (0.0) | A string to parse, or a number to convert. No argument returns 0.0. Objects implementing __float__ are also accepted. |
Return value
float — A double-precision floating-point number. Parses a string with optional sign, decimal point, scientific notation, or one of "inf" / "nan" (case-insensitive).
Common patterns
Parse user input safely
Wrap in try/except — bad input raises ValueError.
try: value = float(raw) except ValueError: value = default
Int → float promotion
Turn an int into a float without arithmetic.
ratio = float(counter) / total
Guard against inf/nan
Special float values slip through parsing silently — filter them.
x = float(raw) if not math.isfinite(x): raise ValueError("must be finite")
Examples
1. Simple number
float("3.14")
Returns
3.142. Integer string
float("42")
Returns
42.03. Scientific notation
float("2.5e10")
Returns
25000000000.04. Whitespace stripped
float(" 3.14 ")
Returns
3.145. Underscores allowed
float("1_000_000.5")
Returns
1000000.56. Infinity
float("inf")
Returns
inf7. NaN
float("nan")
Returns
nan8. No argument
float()
Returns
0.09. Invalid raises
float("abc")
Returns
ValueError: could not convert string to float: 'abc'Pitfalls
1. "inf" and "nan" parse silently
Both are valid float strings in Python — case-insensitive. Reading a CSV or form field into float() with no validation can silently produce inf or nan, which then breaks downstream math in confusing ways.
Silent inf
value = float(user_input) # user typed "inf" total = value + 100 print(total)
inf # arithmetic quietly poisoned
Reject non-finite
import math value = float(user_input) if not math.isfinite(value): raise ValueError("finite value required")
safe
2. Binary floats cannot represent most decimals exactly
float("0.1") is not exactly 0.1 — it is the nearest IEEE 754 double. Accumulated arithmetic drifts. For exact decimals, use Decimal.
Not equal
float("0.1") + float("0.2") == 0.3
False
Decimal for money
from decimal import Decimal Decimal("0.1") + Decimal("0.2") == Decimal("0.3")
True
3. Empty string raises ValueError
float() with no argument returns 0.0. float("") is a ValueError. Blank form fields need explicit handling.
Blank field
float("")
ValueError: could not convert string to float: ''
Guard empty
value = float(s) if s else 0.0
0.0 on blank
4. Trailing junk is a ValueError, not a partial parse
float() is strict — "3.14abc" does not parse to 3.14 with a warning. It raises. Use a regex or a proper parser for "pull the number out" scenarios.
Strict parse
float("3.14abc")
ValueError: could not convert string to float: '3.14abc'
Extract first
import re m = re.search(r"[-+]?\d+(\.\d+)?", raw) value = float(m.group()) if m else default
extract then parse
When to use
Use it
- Parsing user or file input as a floating-point number
- Converting int to float for division without integer truncation
- Reading numeric config values
- Building floats from string data with scientific notation
Reach for something else
- Untrusted input where inf/nan would break downstream → validate with math.isfinite
- Exact decimal arithmetic (money) → Decimal
- Extracting numbers from mixed text → regex first, then float
- You want an integer → int() (float() first is a round-trip you did not need)
Notes
Complexity
O(n) in the input string length
Return
float — always double precision, regardless of input
CPython impl
Objects/floatobject.c :: float_new — dispatches to __float__ or string-parses
Memory
Allocates one float object
Thread-safe
Yes — a pure computation
FAQ
There is no builtin str.isfloat. Convention is try/except — Python code embraces "easier to ask forgiveness than permission".
def is_float(s): try: float(s) return True except ValueError: return False
History
1.0
float() has been a builtin since Python 1.0.
3.6
Underscore separators in numeric literals accepted by float() as well.