1

I am trying to validate a user input, and the user input is required to be positive integers including floating point numbers. I tried with isdigit(), it validated all the non-numeric inputs and negative integers as well but could not validate the floating point numbers. Below is my code

 def is_number(s):
     while (s.isdigit() == False):
       s = input("Enter only numbers, not less than 0 : ")
 return float(s)

#method call

 while('true'):
      membershipFee = is_number(input('Enter the base membership fee, or zero to quit: '))
              
2
  • Should a floating point number return float or int. If int should it always round down? Commented Aug 16, 2020 at 2:57
  • ohh thanks for pointing out, that should be float ..cheers Commented Aug 16, 2020 at 3:13

4 Answers 4

1

You can try the conversion and catch any errors. If python's happy, you're happy.

def is_number(s):
    while True:
        try:
            retval = float(s)
            if s >= 0.:
                return s
        except ValueError:
            pass
        s = input("Enter only numbers, not less than 0 : ")
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to use isdigit(), you can't use it on a float. One possible solution is to use a regex to validate your floats.

Using isdigit for floats?

Comments

0

You can try to do something like this:

#check if there is only one decimal place and check if it is not negative
s = input('Enter the number :')
if s.replace('.','',1).isdigit() and '-' not in s:
    print ('OK to process')
else:
    print ('not OK to process')

This will ensure that you will have the kind of numbers you need.

Comments

0

You should try this

def isNumber(f):
    return all([p.isdigit() for p in [f[:f.find('.')], f[f.find('.')+1:]] if len(p)])

print(isNumber('12.543'))
print(isNumber('185'))
print(isNumber('.2341'))
print(isNumber('163.'))
print(isNumber('14.356.67'))

Comments

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.