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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With