How to Convert a String to a Float in Python
float(text), for example float("3.14") returns 3.14. Text that is not a number, such as "abc" or "1,234.5", raises a ValueError.Prices, measurements and sensor readings usually arrive as text from a file, a form or input(). To calculate with them you need a number, and float() converts a decimal string to a floating point number. It is the decimal counterpart of converting a string to an int.
It accepts more formats than most people expect, but it does not understand thousands separators or currency symbols, so real-world data often needs a little cleaning first. See Python numbers for background on floats.
| Syntax | float(text) |
|---|---|
| Returns | A new float |
| Fails with | ValueError if the text is not a valid number |
| Accepts | Whitespace, sign, decimals, exponents like 1e3, and "inf" or "nan" |
Basic conversion with float()
Whole numbers in text also work and become floats. Leading and trailing whitespace is ignored.
print(float("3.14"))
print(float(" 42 "))
print(float("-0.5"))
print(float("1e3"))Clean text with commas or currency symbols
float("1,234.50") fails because of the comma, and so does "$9.99". Remove what does not belong, then convert. Use replace() or strip() (see string methods).
raw = "$1,234.50"
clean = raw.replace("$", "").replace(",", "")
print(float(clean))Handle invalid input with try and except
For anything typed by a user, catch the ValueError and respond sensibly. Remember that float("nan") and float("inf") are valid, so check them with math.isfinite() if they should not be allowed.
Floats and money: use Decimal when exact cents matter
Floats store binary approximations, so 0.1 + 0.2 is 0.30000000000000004. For exact decimal amounts, such as money, convert the string to decimal.Decimal instead.
from decimal import Decimal
print(float("0.1") + float("0.2"))
print(Decimal("0.1") + Decimal("0.2"))What float() accepts and rejects
| String | `float()` result |
|---|---|
"3.14" | 3.14 |
"10" | 10.0 |
".5" | 0.5 |
"2.5e-3" | 0.0025 |
"1,234.5" | ValueError |
"12abc" | ValueError |
"" | ValueError |
Examples you can run
Press Run, then edit the code and run it again.
Convert prices and add them
Convert each text value and then use normal arithmetic.
prices = ["19.99", "5.50", "3"]
total = sum(float(p) for p in prices)
print(total)
print(f"{total:.2f}")Expected output28.49
28.49
Read a decimal from the user
input() returns text, so convert it with float().
height = float(input("Height in m: "))
print("In cm:", round(height * 100))Expected outputHeight in m: 1.75
In cm: 175
Edge case: safe conversion helper
Return None for text that cannot be converted.
def to_float(text):
try:
return float(text)
except ValueError:
return None
print(to_float("2.5"))
print(to_float("1,5"))
print(to_float("abc"))Expected output2.5
None
None
Common mistakes
Leaving a thousands separator in the string
✗ Wrong
value = float("1,234.5")✓ Right
value = float("1,234.5".replace(",", ""))
print(value)Remove the commas first with replace(",", "").
Using a decimal comma
✗ Wrong
value = float("3,14")✓ Right
value = float("3,14".replace(",", "."))
print(value)Python only understands the dot as decimal separator. Replace the comma with a dot.
Doing arithmetic on the string
✗ Wrong
print("2.5" * 2)✓ Right
print(float("2.5") * 2)Convert with float() before calculating.
How to Convert a String to a Float in Python: questions people ask
How do I convert a string to a float in Python?
Pass the string to float(), for example float("2.75") gives 2.75.
Why does float() raise ValueError: could not convert string to float?
The text is not a valid number, usually because it contains a comma, a currency symbol, letters or is empty. Clean it first or catch the error.
Should I use float or Decimal for prices?
Use Decimal when you need exact cents, because floats cannot represent values like 0.1 exactly. Floats are fine for measurements and scientific work.
Keep learning
Step-by-step lessons:
Python CastingPython NumbersPython ValueError
Related:
How to Convert a String to an Int in PythonHow to Convert a Float to an Int in PythonHow to Convert an Int to a String in Python
More in converting data:
How to Convert a String to an Int in PythonHow to Convert an Int to a String in PythonHow to Convert a List to a String in PythonHow to Convert a String to a List in PythonHow to Convert a Float to an Int in PythonHow to Convert a List to a Dictionary in PythonHow to Convert a Tuple to a List in PythonHow to Convert a String to a Datetime in Python See all →