Solved – ValueError: could not convert string to float
Posted on: March 07, 2021 by Ariessa Norramli
In this article, you will learn how to solve ValueError: could not convert string to float.
Let’s look at code examples that produce the same error.
float('')
# Traceback (most recent call last):
# File "example.py", line 2, in <module>
# ValueError: could not convert string to float: ''
float('1,200')
# Traceback (most recent call last):
# File "example.py", line 6, in <module>
# ValueError: could not convert string to float: '1,200'
float('fd')
# Traceback (most recent call last):
# File "example.py", line 11, in <module>
# ValueError: could not convert string to float: 'fd'
How to Solve ValueError: could not convert string to float
In order to solve it, you can use the try...except
block.
a = 123
try:
float(a)
print("Input is a valid number")
except:
print("Input must be a valid number. Non-special characters, commas and spaces are not accepted.")
Share on social media
//