The easiest way is to convert the string to float with float():
>>> float('42.666')
42.666
If it cannot be converted to float, you will get ValueError:
>>> float('Not a float')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'Not a float'
Using the try/ block is exceptgenerally considered the best way to handle this:
try:
width = float(width)
except ValueError:
print('Width is not a number')
Note that you can also use is_integer()on float()to check if it is integer:
>>> float('42.666').is_integer()
False
>>> float('42').is_integer()
True
source
share