/errors/python/valueerror-could-not-convert-string-to-float
ValueError: could not convert string to float: '12,5'
- tool
- Python
- exit code
- 1
- versions
- Python 3.x
- os
- any
ValueError: could not convert string to float: '12,5' means float() received text that is not a valid number. The text after the colon is exactly what Python failed to read, so look at it first: a decimal comma, a thousands separator, a currency sign, a unit, or nothing at all. Clean the text, then convert.
Reproduce it
python3 - <<'PY'
for text in ['12.5', '12,5', '']:
try:
print(repr(text), '->', float(text))
except ValueError as e:
print(repr(text), '->', type(e).__name__ + ': ' + str(e))
raise SystemExit(1)
PYOutput · exit 1
'12.5' -> 12.5 '12,5' -> ValueError: could not convert string to float: '12,5' '' -> ValueError: could not convert string to float: ''
The first value converts. The other two show the typical failures. An empty string gives could not convert string to float: '', which is easy to misread because the quotes look empty.
What float() accepts
| Input | Result | Why |
|---|---|---|
| '12.5', ' 12.5 ', '-3' | Works | Surrounding whitespace and a sign are allowed |
| '1e3', '1_000.5' | Works | Exponent and digit underscores are allowed |
| 'inf', 'nan' | Works | Special values, in any letter case |
| '12,5', '1,000.5' | ValueError | Commas are never accepted |
| '$12.50', '12.5kg', '50%' | ValueError | Symbols and units are not numbers |
| '', 'N/A', 'null' | ValueError | No digits to read |
Fixes
Decimal comma and thousands separators
Decide which character is the decimal separator for your source, then normalise:
python3 - <<'PY'
print(float('12,5'.replace(',', '.')))
print(float('1,000.5'.replace(',', '')))
print(float('$12.50'.lstrip('$')))
PYOutput
12.5 1000.5 12.5
For European text such as 1.234,5 remove the dot first and then replace the comma: s.replace('.', '').replace(',', '.'). Do not apply that rule to English-format numbers.
Empty and placeholder values
Decide what a missing value means for your program, then handle it before converting:
python3 - <<'PY'
def to_float(text, default=None):
text = text.strip()
if text in ('', 'N/A', 'null', '-'):
return default
return float(text)
print(to_float(''), to_float('N/A', 0.0), to_float(' 3.5 '))
PYOutput
None 0.0 3.5
Report the bad value
When the data comes from users or files, catch the error and keep the text in your message so the row can be found:
try:
price = float(raw)
except ValueError:
raise SystemExit(f"invalid price in line {line_no}: {raw!r}")Money and exactness
Binary floats cannot store most decimal fractions exactly. For amounts of money, use decimal.Decimal(text), which also raises an error (decimal.InvalidOperation) on invalid text.
Prevention
Validate input at the boundary: read CSV with explicit types, state the number format in your documentation, and reject unknown text early with a message that shows the value.
FAQ
What text does float() accept?
Optional whitespace and sign, digits with an optional dot, an optional exponent such as 1e3, and the words inf, infinity and nan in any case. Underscores between digits are accepted too, as in 1_000.5.
Why does float('1,000.5') fail?
Python has no locale-aware parsing in float(). Remove the comma with replace(',', '') first, or parse with locale.atof after calling locale.setlocale.
How do I convert a whole column safely?
pandas.to_numeric(series, errors='coerce') turns invalid values into NaN so you can inspect or drop them instead of stopping at the first one.