Computer >> Computer tutorials >  >> Programming >> Python

How to check if a string can be converted to float in Python?


To parse a string to float, you can use the following:

try:
    print float('112.15')
except ValueError:
    print 'Cannot parse'

This will give you the output:

112.15

If your string cant be parsed, it'll throw a value error.

You can create a wrapper method that returns booleans for strings you give it. For example,

def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False
print (isfloat('112.5'))

OUTPUT

True