pythonformatdecimal

python Decimal - checking if integer


I am using the Decimal library in Python, and printing out the values using format(value, 'f'), where value is a Decimal. I get numbers in the form 10.00000, which reflects the precision on the decimal. I know that float supports is_integer, but there seems to be a lack of a similar API for decimals. I was wondering if there was a way around this.


Solution

  • 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