float()
Turns text like "3.14" or a whole number into a floating-point number, the type Python uses for prices, measurements and other decimals.
float(x=0.0)float() makes a decimal number, called a float (short for floating-point number). float("2.5") gives 2.5, and float(7) gives 7.0.
Use it on text that holds a decimal, such as a price typed by the user or a value read from a CSV file. It also understands scientific notation ("1e3" is 1000) and the special values "inf" and "nan".
Floats are stored in binary, and most decimal fractions cannot be stored exactly. That is why 0.1 + 0.2 prints 0.30000000000000004. For everyday work, format the result to the decimals you need; for money where every cent must be exact, use the decimal module.
Parameters
| Parameter | What it is |
|---|---|
xoptional, default 0.0 | A string holding a number (spaces around it are fine; a decimal point, not a comma), an int, or another float. With nothing, float() gives 0.0. |
Return value
A float.
Examples
1Text and whole numbers to floats
print(float("3.14"))
print(float(" 2.50\n"))
print(float(7))
print(float("1e3"))
print(float("-0.5"))3.14 2.5 7.0 1000.0 -0.5
Python prints the shortest form that means the same number, so "2.50" comes back as 2.5.
2Average price from a list of strings
prices = ["4.50", "12.00", "3.25", "6.80"]
numbers = [float(p) for p in prices]
average = sum(numbers) / len(numbers)
print(numbers)
print(f"Average: {average:.2f}")[4.5, 12.0, 3.25, 6.8] Average: 6.64
3Why 0.1 + 0.2 is not 0.3
import math
total = 0.1 + 0.2
print(total)
print(total == 0.3)
print(math.isclose(total, 0.3))
print(round(total, 2) == 0.3)0.30000000000000004 False True True
Never compare floats with == after arithmetic. math.isclose() checks whether two floats are close enough.
4Infinity and not-a-number
big = float("inf")
print(big > 10 ** 300)
print(min(4.2, big))
nothing = float("nan")
print(nothing == nothing)True 4.2 False
inf is larger than every number, handy as a starting value when you search for a minimum. nan is not even equal to itself.
5Exact money with Decimal
When every cent counts, use Decimal from the decimal module, and create it from a string:
from decimal import Decimal
print(0.1 + 0.2)
print(Decimal("0.1") + Decimal("0.2"))
print(float(Decimal("19.99")))0.30000000000000004 0.3 19.99
Common mistakes
Using a comma as the decimal sign
float() only accepts a point. If your data uses commas, replace them first.
text = "1,5"
try:
print(float(text))
except ValueError:
print("ValueError: '1,5' is not a valid float")
print(float(text.replace(",", ".")))ValueError: '1,5' is not a valid float 1.5
Expecting exact decimals
Adding floats can leave tiny errors, so totals may print with many digits. Format when you display, and use Decimal when the exact value matters.
basket = [0.10] * 3
print(sum(basket))
print(f"{sum(basket):.2f}")0.30000000000000004 0.30
Questions people ask
How do I convert a string to a float in Python?
float("3.5"). Wrap it in try / except ValueError if the text may not be a number.
How do I print a float with 2 decimals?
Use an f-string: f"{x:.2f}". This changes only the display; round() changes the value.
How do I convert a float to an int?
int(x) cuts off the decimals (toward zero); round(x) gives the nearest whole number.
How do I check whether a string is a valid float?
Try it: try: float(text) and catch ValueError. String methods like isdigit() reject the decimal point.