Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert float to integer strictly, without rounding?

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?

like image 675
Arthur Avatar asked Jul 18 '19 05:07

Arthur


1 Answers

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'
like image 145
gilch Avatar answered Oct 01 '22 01:10

gilch