Bemjamin Zhuo
Bemjamin Zhuo

Reputation: 91

How to check if a string is a decimal/ float number?

I need to check if a string is of the form of a decimal/ float number.

I have tried using isdigit() and isdecimal() and isnumeric(), but they don't work for float numbers. I also can not use try: and convert to a float, because that will convert things like " 12.32" into floats, even though there is a leading white-space. If there is leading white-spaces, I need to be able to detect it and that means it is not a decimal.

I expect that "5.1211" returns true as a decimal, as well as "51231". However, something like "123.12312.2" should not return true, as well any input with white-space in it like " 123.12" or "123. 12 ".

Upvotes: 4

Views: 4498

Answers (1)

Ruan
Ruan

Reputation: 902

This is a good use case for regular expressions.

You can quickly test your regex patterns at https://pythex.org/ .

import re

def isfloat(item):

    # A float is a float
    if isinstance(item, float):
        return True

    # Ints are okay
    if isinstance(item, int):
        return True

   # Detect leading white-spaces
    if len(item) != len(item.strip()):
        return False

    # Some strings can represent floats or ints ( i.e. a decimal )
    if isinstance(item, str):
        # regex matching
        int_pattern = re.compile("^[0-9]*$")
        float_pattern = re.compile("^[0-9]*.[0-9]*$")
        if float_pattern.match(item) or int_pattern.match(item):
            return True
        else:
            return False

assert isfloat("5.1211") is True
assert isfloat("51231") is True
assert isfloat("123.12312.2") is False
assert isfloat(" 123.12") is False
assert isfloat("123.12 ") is False
print("isfloat() passed all tests.")

Upvotes: 3

Related Questions