python Decimal - checking if integer
Try math.floor(val) == val
or val == int(val)
.
You could use the modulo operation to check if there is a non-integer remainder:
>>> from decimal import Decimal
>>> Decimal('3.14') % 1 == 0
False
>>> Decimal('3') % 1 == 0
True
>>> Decimal('3.0') % 1 == 0
True
The mathematical solution is to convert your decimal number to integer and then test its equality with your number.
Since Decimal
can have an arbitrary precision, you should not convert it to int
or float
.
Fortunately, the Decimal
class has a to_integral_value
which make the conversion for you. You can adopt a solution like this:
def is_integer(d):
return d == d.to_integral_value()
Example:
from decimal import Decimal
d_int = Decimal(3)
assert is_integer(d_int)
d_float = Decimal(3.1415)
assert not is_integer(d_float)