ValuePython Error

ValueError

ValueError: could not convert string to float: 'abc'

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    price = float("$19.99")
ValueError: could not convert string to float: 'abc'

What causes this error

A string passed to float() does not represent a valid floating-point number. The string contains non-numeric characters, multiple decimal points, or locale-specific formatting.

How to fix it

Validate strings before conversion with try/except ValueError. Strip whitespace and currency symbols. Handle locale-specific formats. Use pandas for robust parsing of data files with inconsistent formats.

Code that causes this error

Broken
price = float("$19.99")

Fixed code

Fixed
raw = "$19.99"
cleaned = raw.replace("$", "").replace(",", "")
try:
    price = float(cleaned)
except ValueError:
    price = 0.0

About ValueError

This ValueError occurs when `float()` receives a string that does not represent a valid floating-point number. Valid float strings include '3.14', '-2.5', '1e10', 'inf', '-inf', and 'nan'. Invalid strings include words, strings with multiple decimal points, strings with currency symbols or commas, and empty strings.

This error commonly appears in data processing when reading CSV files with missing or malformed numeric data, when parsing user input, and when processing locale-specific number formats that use commas as decimal separators. The `locale` module can help parse locale-formatted numbers, and libraries like `pandas` have robust parsing that handles various number formats and missing values automatically.

Common scenarios

1

Converting user input strings to numbers without validation

2

Unpacking iterables with an unexpected number of elements

3

Passing out-of-range values to mathematical functions

4

Processing data files with inconsistent or malformed records

Related errors