In Python, float(x) converts x to a floating-point number: float("3.14") is 3.14 and float(7) is 7.0. With no argument it returns 0.0.
Strings may use scientific notation ("1e3"), surrounding whitespace, and the special words "inf", "-infinity", and "nan" in any case. Floats are binary approximations with about 15 to 17 significant digits, so some decimal values cannot be stored exactly.
float is a built-in type (a class) that you call like a function: each call creates a new float object. Like every built-in, it lives in the builtins module and is always available without an import.
Syntax
Convert an int or parse text.
python
value = float(x)
Call
What it does
float("3.14")
Returns 3.14.
float("1e3")
Returns 1000.0.
float(7)
Returns 7.0.
float("inf")
Returns positive infinity.
Compare floats with math.isclose(a, b) instead of == when they come from calculations.
Library declarations
python
float(x=0.0, /)
# class float: float is a built-in type
Parameters
Parameter
Description
x
Optional. An int, a float, a string, or an object with __float__() or __index__(). Default 0.0.
Return Value
Return Value
Description
float
The floating-point value, possibly inf or nan.
Python Examples
Example 1 — Convert Strings and Ints to float
Parse plain decimals, padded text, scientific notation, and whole numbers.
python
values = ["3.14", " 2.5 ", "1e3", "-0.001", "7"]
for text in values:
print(repr(text), "->", float(text))
print(float(10), float())
Infinity beats everything.float("inf") is greater than any int, even 10 to the 100th.
Negative infinity. Negating it prints -inf.
NaN is never equal.nan == nan is False, so use math.isnan() to detect it.
Bad text. A unit suffix or an empty string raises ValueError; !r shows the exact input.
Frequently Asked Questions
Call float("3.14"). It accepts whitespace, a sign, scientific notation like "1e-3", and the words inf and nan.
Floats are stored in binary, and 0.1 and 0.2 have no exact binary form. The small errors show up in the sum. Use math.isclose() to compare or round() to display.
Use math.isnan(x). x == float("nan") is always False because NaN is not equal to itself.
Remove the thousands separator first: float("1,234.5".replace(",", "")). float() does not accept commas.
Use decimal.Decimal for money and other values that must be exact in base 10. Floats are faster and fine for measurements and science.