How to know if a Decimal is an integer

Given that I have an x variable which I already know its type as decimal.Decimal.
Any quick way to know that it is an integer, like Decimal(5)?

I know that I can do

x == int(x)

but is there any way like x.is_integer()?

Decimal(5) % 1 == 0
Decimal(“5.00001”) % 1 == 0

although that will raise if the Decimal is INF, unless you
trap decimal.InvalidOperation.

You could also try:

x == Decimal("5.0001")
x == math.trunc(x)

although that will raise if x is a NAN or INF.

Try this:

def isinteger(x):
    with decimal.localcontext() as ctx:
        ctx.traps[decimal.InvalidOperation] = False
        return x % 1 == 0
1 Like


from decimal import Decimal
Decimal("5.0").as_integer_ratio()[1] == 1

Which has the benefit of also working for fractions.Fraction (for Python 3.8) and float. Ditto on @steven.daprano’s note on infinities and NaNs