ValueError: could not convert string to float
ValueError: could not convert string to float in Python means float() was given text that is not a plain number. Common culprits are commas (1,200), currency signs (₹250), units (12kg) and empty strings.
How do I fix ValueError: could not convert string to float?
ValueError: could not convert string to float means float() got text that is not a plain number. The text is shown in quotes at the end of the message. Commas like '1,200', symbols like '₹250', units like '12kg' and empty strings '' are common. Remove them with .replace() before calling float(), and handle empty text separately.
- 1. Read the quoted textThe message ends with the exact text that failed. '' means the input or CSV cell was empty.
- 2. Strip extra charactersRemove commas, currency signs and units first, for example float(text.replace(",", "")).
- 3. Catch bad inputFor user input, wrap float() in try/except ValueError and ask again instead of crashing.
What does ValueError: could not convert string to float mean?
float() understands text like "3.5", "-2" and " 7 " (spaces at the ends are fine). It does not understand anything else. The message shows the exact text it got, in quotes, at the end: could not convert string to float: '1,200'. Seeing '' there means the text was empty, usually a blank input or an empty cell in a CSV.
Why does ValueError: could not convert string to float happen?
1. Commas as thousand separators
"1,200" and "1,20,000" are normal to read but float() rejects the commas.
Breaks
price = float("1,20,000")Works
price = float("1,20,000".replace(",", "")) # 120000.02. Currency symbols or units in the text
Only digits, a sign and one decimal point are allowed.
Breaks
cost = float("₹250")
weight = float("12kg")Works
cost = float("₹250".replace("₹", ""))
weight = float("12kg".removesuffix("kg"))3. An empty string
The user pressed Enter without typing, or a CSV cell was blank.
Breaks
value = float(input("Amount: "))Works
text = input("Amount: ").strip()
value = float(text) if text else 0.04. A comma used as the decimal point
Some countries write 2,5 for two and a half. Python needs 2.5.
Breaks
float("2,5")Works
float("2,5".replace(",", ".")) # 2.5How to find it in your own code
Checklist: 1) Read the text in quotes at the end of the message; it shows exactly what failed. 2) print(repr(text)) before the conversion to see hidden characters. 3) Remove commas, symbols and units before converting. 4) Handle empty text separately. 5) For user input, wrap it in try/except ValueError and ask again.
Practise type errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.