drop trailing zeros from decimal

前端 未结 9 1904
庸人自扰
庸人自扰 2020-11-29 03:54

I have a long list of Decimals and that I have to adjust by factors of 10, 100, 1000,..... 1000000 depending on certain conditions. When I multiply them there is sometimes

9条回答
  •  囚心锁ツ
    2020-11-29 04:17

    Answer is mentioned in FAQ (https://docs.python.org/2/library/decimal.html#decimal-faq) but does not explain things.

    To drop trailing zeros for fraction part you should use normalize:

    >>> Decimal('100.2000').normalize()
    Decimal('100.2')
    >> Decimal('0.2000').normalize()
    Decimal('0.2')
    

    But this works different for numbers with leading zeros in sharp part:

    >>> Decimal('100.0000').normalize()
    Decimal('1E+2')
    

    In this case we should use `to_integral':

    >>> Decimal('100.000').to_integral()
    Decimal('100')
    

    So we could check if there's a fraction part:

    >>> Decimal('100.2000') == Decimal('100.2000').to_integral()
    False
    >>> Decimal('100.0000') == Decimal('100.0000').to_integral()
    True
    

    And use appropriate method then:

    def remove_exponent(num):
        return num.to_integral() if num == num.to_integral() else num.normalize()
    

    Try it:

    >>> remove_exponent(Decimal('100.2000'))
    Decimal('100.2')
    >>> remove_exponent(Decimal('100.0000'))
    Decimal('100')
    >>> remove_exponent(Decimal('0.2000'))
    Decimal('0.2')
    

    Now we're done.

提交回复
热议问题