5

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

1
  • 1
    If you want to know whether or not the number you are testing has a value to the right of the decimal point, you can use modulus 1 and it the answer is not 0 it is ia decimal. 5 % 1 == 0 and 5.25 % 1 = 0.25 Commented Jul 3, 2018 at 3:20

6 Answers 6

5

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

3 Comments

Hi, 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?
How 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!
Be aware that int(12.3) also works fine but 12.3 is a float, not an integer.
4

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')

Comments

2

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.

Comments

1

You can use isinstance:

if isinstance(var, float):
    ...

1 Comment

when 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?
1

You can check it by converting to int:

    try:
       val = int(userInput)
    except ValueError:
       print("That's not an int!")

1 Comment

Thanks, that solved my issue :)
0

(one) fast anwer

a=1
b=1.2
c=1.0
d="hello"

l=[a,b,c,d]

for i in l:
  if type(i) is float:
    print(i)

 #result : 1.0, 1.2

long answer : What's the canonical way to check for type in python?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.