Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Python raises ValueError: could not convert string to float when float() receives a string whose contents do not follow Python’s numeric format. The fix depends on what the string contains: inspect the raw value, remove only known decoration, parse separators using the source’s format, or choose a parser suited to a column or decimal arithmetic.

What the error means

A ValueError means an operation received an argument of an acceptable type but an unacceptable value. A string is a valid argument to float(), but its contents must match the numeric syntax Python recognizes. That syntax permits a decimal number, an optional sign, surrounding whitespace, an exponent, and spellings of infinity and NaN. Words, currency symbols, and incompatible punctuation do not qualify. See Python’s float() reference and its explanation of ValueError.

For example, float("-2.5e3") can be parsed, while float("$2.50") cannot. The error identifies a parsing failure; it does not tell you which character or record caused it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

1. Inspect the exact string before converting it

Print the value with repr() so invisible characters are visible. A tab, newline, nonbreaking space, or unexpected label may be difficult to notice in ordinary output.

value = "12.5u00a0"
print(repr(value))
number = float(value)

Check the output and trace the value back to its source, such as a file, form, API response, or database field. If a conversion fails in a batch, identify the offending record rather than catching the exception and discarding the context.

2. Remove only known decoration

Python already allows whitespace at the beginning and end of a numeric string. Calling strip() is useful when normalizing input, but it will not remove a currency symbol, unit, or descriptive word.

value = " 12.5 "
number = float(value.strip())

price = "$12.50"
number = float(price.removeprefix("$"))

Only remove decoration whose meaning and position are known. Broad replacements can corrupt a value: deleting every comma, for example, may turn a decimal-comma value into a different number. If the input includes a unit or other text, validate that format and remove the expected part explicitly before parsing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Parse separators using the input’s convention

Commas and periods can mark different things in different formats. 1,234.50 uses a comma for grouping and a period for decimals; 1.234,50 uses the reverse convention. Neither should be normalized until you know the source format. For a fixed, documented format, write an explicit normalization rule and validate it against the expected pattern.

Use a locale when the source is locale-defined

For input that follows a known numeric locale, configure that locale in the application and use locale.atof(). It interprets separators according to the active LC_NUMERIC setting; it does not automatically guess a string’s locale.

import locale

# Set the intended numeric locale in the application before parsing.
number = locale.atof("1.234,50")

Choose the locale that matches the data source and deployment environment. Python documents locale.atof() and its locale-dependent behavior.

4. Parse a pandas column deliberately

For a pandas Series or other one-dimensional data, pd.to_numeric() raises an error for invalid values by default. This fail-fast behavior is useful when every input is expected to be numeric. If invalid entries should become missing values so you can inspect the rest of the data, use errors="coerce" and then locate the affected rows.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import pandas as pd

values = pd.Series(["1.5", "not available", "2.0"])
parsed = pd.to_numeric(values, errors="coerce")
bad_rows = values[parsed.isna()]

print(bad_rows)

Coercion is not a repair: invalid values become NaN and still need review, correction, or an explicit missing-data policy. Also account for pandas’ warning that very large values may lose precision when stored in array-backed numeric types. See the pandas.to_numeric() documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

5. Use Decimal when decimal arithmetic matters

Binary floating-point values are not exact representations of many decimal fractions. If your calculation requires decimal arithmetic, parse a valid decimal string with Decimal rather than converting it to float.

from decimal import Decimal

amount = Decimal("12.50")

Decimal has its own accepted string syntax; it is not a general parser for currency-formatted input such as "$12.50". Remove and validate any known decoration before constructing the decimal. Python documents the Decimal constructor and decimal arithmetic.

Choose the fix that matches the input

Situation Approach Watch out for
You do not know what the string contains Inspect it with repr(), then trace the source. Do not suppress the failure without identifying the bad record.
It has known whitespace or a known prefix Strip surrounding whitespace or remove that specific decoration. Do not use blanket replacements that can change numeric meaning.
It uses locale-specific separators Use the matching locale or a validated rule for a fixed format. Do not assume punctuation has the same meaning across sources.
You are converting a pandas column Use pd.to_numeric(); choose fail-fast parsing or coercion intentionally. Coerced invalid values become NaN and require follow-up.
Decimal representation is important Construct a Decimal from a valid decimal string. It does not parse arbitrary currency-formatted text.

Do not use eval() as a conversion shortcut

eval() is not a safe way to parse a number from text. It evaluates Python expressions rather than applying a numeric conversion rule, creating a security risk and adding unnecessary overhead. Use a parser that matches the input format; Python’s FAQ explains the risks of eval().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.