To convert a string to a float in Python, pass it to float(): float("19.99") returns 19.99. If the string contains thousands separators, remove them first (float("1,234.5".replace(",", ""))), and wrap the call in try/except ValueError when the text may not be a number. This guide shows how to convert string to float in Python in every common situation, and how to fix ValueError: could not convert string to float.
All examples were run with Python 3.12.5 and pandas 3.0.6 in the Windows Command Prompt. See the Python documentation for float() and locale.atof().
Convert a string to a float with float()
price = "19.99"
rate = float(price) # string -> float
print(rate, type(rate))
print(float(" 42 ")) # spaces and newlines around the number are ignored
print(float("-3.5e2")) # scientific notation works
print(float("1_000.5")) # underscores between digits too (Python 3.6+)
Output:
19.99 <class 'float'>
42.0
-350.0
1000.5
float() accepts leading and trailing whitespace, a sign, a decimal point, an exponent (e or E), underscores between digits, and the words nan, inf and infinity. Anything else raises a ValueError.
ValueError: could not convert string to float
This error means the text contains something float() cannot read. These are the usual culprits:
values = ["3.14", "", "None", ".", "abc", "1,234.50", "12%", "$9.99"]
for v in values:
try:
print(f"{v!r:>12} -> {float(v)}")
except ValueError as e:
print(f"{v!r:>12} -> ValueError: {e}")
Output:
'3.14' -> 3.14
'' -> ValueError: could not convert string to float: ''
'None' -> ValueError: could not convert string to float: 'None'
'.' -> ValueError: could not convert string to float: '.'
'abc' -> ValueError: could not convert string to float: 'abc'
'1,234.50' -> ValueError: could not convert string to float: '1,234.50'
'12%' -> ValueError: could not convert string to float: '12%'
'$9.99' -> ValueError: could not convert string to float: '$9.99'

float() accepts, and the exact error for the ones it does not.| Error message ends with | Cause | Fix |
|---|---|---|
'' | An empty string (blank cell, empty input) | Check if text.strip(): or return a default |
'None' / 'N/A' | A placeholder written as text | Map it to None or float("nan") |
'1,234.50' | Thousands separator | text.replace(",", "") |
'12%', '$9.99' | Symbols around the number | Remove them with re.sub() or strip("$%") |
'.', 'abc' | Not a number at all | Validate or skip the value |
Passing None itself (not the string) raises a different error: TypeError: float() argument must be a string or a real number, not 'NoneType'.
Convert a string with commas to float
Remove the thousands separator before converting. For European formats, where the comma is the decimal separator, swap the characters, or use the locale module:
import locale
us = "1,234,567.89" # comma as thousands separator
print(float(us.replace(",", "")))
eu = "1.234.567,89" # European: dot thousands, comma decimals
print(float(eu.replace(".", "").replace(",", ".")))
locale.setlocale(locale.LC_NUMERIC, "de_DE") # or let the locale module do it
print(locale.atof(eu))
locale.setlocale(locale.LC_NUMERIC, "en_US")
print(locale.atof(us))
Output:
1234567.89
1234567.89
1234567.89
1234567.89

replace() and locale.atof().Locale names differ between systems ("de_DE" works on Windows and most Linux systems with that locale installed). setlocale() changes a global setting for the whole program, so prefer replace() inside libraries and web apps.
A safe string to float function
For messy data (prices, percentages, blanks), clean the text and return a default instead of crashing:
import re
def to_float(text, default=None):
"""Convert text such as '$1,299.50', ' 12 % ' or '' to a float, or return default."""
if text is None:
return default
cleaned = re.sub(r"[^0-9eE.+-]", "", str(text)) # drop $, commas, %, spaces ...
try:
return float(cleaned)
except ValueError:
return default
for v in ["$1,299.50", " 12 % ", "", None, "N/A", "7.5e3", "-0.25"]:
print(f"{v!r:>12} -> {to_float(v)}")
Output:
'$1,299.50' -> 1299.5
' 12 % ' -> 12.0
'' -> None
None -> None
'N/A' -> None
'7.5e3' -> 7500.0
'-0.25' -> -0.25
Convert user input to float
text = input("Enter a price: ")
try:
price = float(text.replace(",", ""))
print(f"Price with 18% tax: {price * 1.18:,.2f}")
except ValueError:
print(f"'{text}' is not a number")
Output (the user typed 2,499.90):
Enter a price: 2,499.90
Price with 18% tax: 2,949.88

Convert a list of strings to floats
readings = ["21.5", "22.0", "", "23.4", "error", "24.1"]
numbers = [float(r) for r in readings if r.replace(".", "", 1).isdigit()] # skip non-numbers
print(numbers)
print("average:", round(sum(numbers) / len(numbers), 2))
Output:
[21.5, 22.0, 23.4, 24.1]
average: 22.75
str.isdigit() alone rejects negative numbers and exponents; for those, use the to_float() function above in the list comprehension.
Convert a pandas column from string to float
pd.to_numeric(..., errors="coerce") converts a whole column and turns values it cannot parse into NaN, so one bad cell does not stop the conversion:
import pandas as pd
df = pd.DataFrame({"product": ["A", "B", "C", "D"],
"price": ["1,299.00", "849.50", "N/A", "2,050.75"]})
df["price_float"] = pd.to_numeric(df["price"].str.replace(",", ""), errors="coerce") # bad values -> NaN
print(df)
print(df.dtypes)
Output:
product price price_float
0 A 1,299.00 1299.00
1 B 849.50 849.50
2 C N/A NaN
3 D 2,050.75 2050.75
product str
price str
price_float float64
dtype: object

N/A turned into NaN.When reading files, pd.read_csv("file.csv", thousands=",") (and decimal="," for European files) converts the numbers while loading.
Check if a string can be converted to float
def is_float(text):
try:
float(text)
return True
except (TypeError, ValueError):
return False
for v in ["3.14", "10", "1e5", "nan", "abc", "", "1,5"]:
print(f"{v!r:>7} {is_float(v)}")
Output:
'3.14' True
'10' True
'1e5' True
'nan' True
'abc' False
'' False
'1,5' False
Note that "nan" counts as a valid float. For money, consider decimal.Decimal(text) instead of float, because binary floats cannot store values like 0.1 exactly.
Related Python conversion tutorials:
- Convert a dictionary to a string in Python
- Convert datetime to string in Python
- Remove characters from a string in Python
- Get the first and last digit of a number
Frequently asked questions
How do I convert a string to a float in Python?
Use float(text), for example float("3.14"). Remove commas and symbols first, and handle ValueError for text that is not a number.
How do I fix ValueError: could not convert string to float?
Look at the value at the end of the message. Strip empty strings and placeholders like ‘N/A’, remove commas and symbols such as $ or %, or use a try/except that returns a default.
How do I convert a string with a comma to a float?
For 1,234.56 use float(text.replace(",", "")). For 1.234,56 use float(text.replace(".", "").replace(",", ".")) or locale.atof().
Why do I get could not convert string to float: ”?
The string is empty, usually from a blank CSV cell or empty input. Check if text.strip() before converting.
How do I convert a pandas column from string to float?
pd.to_numeric(df["col"].str.replace(",", ""), errors="coerce") converts the column and sets invalid values to NaN.
How do I check if a string is a float in Python?
Try float(text) inside try/except and return True or False; isdigit() does not accept decimal points or signs.