5

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 ".

1
  • If you don't want to just accept what float accepts, you need to give a clear specification of what is acceptable. For example: should .12 be accepted? 12.? 1e6? +1.23? 123_456.789? −123 (with a Unicode minus sign)? Commented Feb 17, 2019 at 7:38

1 Answer 1

3

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.")
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I did not even know this was a thing. Thank you for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.