6

I wish to find a way to achieve the following: With the likes of 5.0, return 5. With the likes of 5.1, which cannot equal any integer, return Error.

Currently I use int() together with an "if integer != float". However this has problems, for instance I won't be able to tell whether the inequality was caused by the likes of 5.1 or the likes of 1111111111111111.0(and even larger numbers).

Also this is extremely troublesome compared with a potential, simple, one-line command. So is there a command in Python that does this?

Arthur
  • 118
  • 1
  • 9

5 Answers5

12

Float objects in Python have an is_integer() predicate.

def strict_int(x):
    if x.is_integer():
        return int(x)
    raise ValueError

Note that int objects do not have this method. You'll get an attribute error if you try to call this on an int.


If you wanted some error value instead of an exception, you can use a one-liner like this

int(x) if x.is_integer() else 'Error'
gilch
  • 10,813
  • 1
  • 23
  • 28
2

Simply use math as suggested in this answer by @Anthony V like this:

>>> frac, whole = math.modf(5.0) 
>>> if frac ==0.0:
...     print("this is a whole") 
... else: 
...     print("this is not whole and should return the Error") 

This should work easily.

user2906838
  • 1,178
  • 9
  • 20
1

I'm not sure whether there's a more idiomatic way to do this, but intuitively, you can just compare the value of the int and the float and return only when they are equal.

That is

def weird_cast(my_float):
    if int(my_float) == my_float:
        return int(my_float)
    return None # or some error
absolutelydevastated
  • 1,657
  • 1
  • 11
  • 28
0
def return_int(a):
    if int(a)==a:
        print(int(a)) #you can store the integer value in separate variable #also b = int(a)
        #instead of using print you can use return b or int(a)   
    else:
        print('Error') #or you can use return 'Error'

a = 5.0
return_int(a)
Vishal
  • 43
  • 8
0

Maybe another easier way is to minus with the round down number with itself. if the remainder is more than 0.0 and less than 1.0, then we can call it a float otherwise integer

def IntegerSanityCheck ( num ):
    remainder = abs ( round ( num ) - num )
    if ( remainder > 0.0 ) and ( remainder < 1.0 ):
        print "Float"
    else:
        print "Integer"

or you can use math as suggested by user2906838