Using float() you can quickly check if a string is a float. The isnumeric() doesn’t consider numbers with non-ints as numeric. So you have to check with the float() method isnumeric float does not work in Python.
The easiest way is to convert the string to a float with float()
:
float('42.666')
If it can’t be converted to a float, you get a ValueError
:
Using a try
/except
block is typically considered the best way to handle this:
try:
width = float(width)
except ValueError:
print('Width is not a number')
Python isnumeric float example
Simple example code.
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
print(isfloat('s12'))
print(isfloat('1.123'))
print(isfloat('Hello'))
Output:
Do comment if you have any doubts or suggestions on this Python isnumeric method topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.