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

PythonServer Side ProgrammingProgramming

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
raja
Published on 14-Dec-2017 14:41:56
Advertisements