Harry Krek
Harry Krek

Reputation: 91

How to check if a string represents a float number

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)

Upvotes: 7

Views: 21175

Answers (3)

Thomas R
Thomas R

Reputation: 1217

Here another solution without "try" and which is returning a truth-value directly. Thanks to @Cam Jackson. I found this solution here: Using isdigit for floats?

The idea is to remove exactly 1 decimal point before using isdigit():

>>> "124".replace(".", "", 1).isdigit()
True
>>> "12.4".replace(".", "", 1).isdigit()
True
>>> "12..4".replace(".", "", 1).isdigit()
False
>>> "192.168.1.1".replace(".", "", 1).isdigit()
False

Upvotes: 0

Forge
Forge

Reputation: 6834

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

Upvotes: 7

Martin Tournoij
Martin Tournoij

Reputation: 27822

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

Upvotes: 17

Related Questions