4

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
  • 53
  • 1
  • 2
  • 7
  • 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` – jerblack Jul 03 '18 at 03:20

6 Answers6

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!")
Stan Vanhoorn
  • 526
  • 1
  • 4
  • 18
  • 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? – hpj Dec 08 '16 at 12:08
  • 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! – Stan Vanhoorn Dec 08 '16 at 12:13
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')
duck
  • 369
  • 3
  • 17
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.

1

You can use isinstance:

if isinstance(var, float):
    ...
korvinos
  • 509
  • 3
  • 7
  • 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? – hpj Dec 08 '16 at 10:12
1

You can check it by converting to int:

    try:
       val = int(userInput)
    except ValueError:
       print("That's not an int!")
Reza
  • 728
  • 1
  • 10
  • 28
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?

Community
  • 1
  • 1
Soltius
  • 2,162
  • 1
  • 16
  • 28