How to check if a string contains a floating point number

I use this to check if a variable is numeric, I also want to check if it is a floating point number.

if(width.isnumeric() == 1)
+4
source share
2 answers

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
+14
source
def is_float(string):
  try:
    return float(string) and '.' in string  # True if string is a number contains a dot
  except ValueError:  # String is not a number
    return False

Output:

>> is_float('string')
>> False
>> is_float('2')
>> False
>> is_float('2.0')
>> True
>> is_float('2.5')
>> True
+6
source

All Articles