Python - how to test if a users input is a decimal number
27,820
Solution 1
U also could use a Try/Except to check if the variable is an integer:
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
or a float:
try:
val = float(userInput)
except ValueError:
print("That's not an float!")
Solution 2
You can use float.is_integer() method.
Example:
data = float(input("Input number"))
if data.is_integer():
print (str(int(data)) + ' is an integer')
else:
print (str(data) + ' is not an integer')
Solution 3
I found a way of doing this in python but it doesn't work in a new window/file.
>>> variable=5.5
>>> isinstance(variable, float)
True
>>> variable=5
>>> isinstance(variable, float)
False
I hope this helped.
Solution 4
You can use isinstance
:
if isinstance(var, float):
...
Solution 5
You can check it by converting to int:
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
Author by
hpj
Updated on December 09, 2020Comments
-
hpj over 3 years
I am writing a program that needs to check if a users input is a decimal (the users input must be a deciamal number),I was wondering how I could test a varible to see if it contains only a decimal number.
Thanks, Jarvey
-
hpj over 7 yearswhen I do this it will not allow a decimal number but will allow text. what is a way that I can only allow a decimal number like '0.2' or '1.5' to be accepted but an input like 'hello' will be rejected?
-
hpj over 7 yearsHi, thanks for the help, this one seemed to work but it also allows charaters and I want is float numbers, do you have any idea how I could stop characters begin accepted?
-
Stan Vanhoorn over 7 yearsHow do you mean? If I type in anything other than a number it raises the exception. So in this case it prints: That's not an float!
-
hpj over 7 yearsThanks, that solved my issue :)