I'm using this to check if a variable is numeric, I also want to check whether it's a floating point number.
if(width.isnumeric() == 1)
Use the isinstance() function to check if a number is an int or float, e.g. if isinstance(my_num, int): . The isinstance function will return True if the passed in object is an instance of the provided class ( int or float ). Copied!
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.
To check if a string is a valid Float, use the Float. parseFloat() method, with the string to be checked passed as a parameter.
The easiest way is to convert the string to a float with float()
:
>>> float('42.666')
42.666
If it can't be converted to a float, you get a 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 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')
Note you can also use is_integer()
on a float()
to check if it's an integer:
>>> float('42.666').is_integer()
False
>>> float('42').is_integer()
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With