How to check if a string represents a float number

Viewed 16569

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)
3 Answers

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
Related