drop trailing zeros from decimal

前端 未结 9 1894
庸人自扰
庸人自扰 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:12

    Answer from the Decimal FAQ in the documentation:

    >>> def remove_exponent(d):
    ...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
    
    >>> remove_exponent(Decimal('5.00'))
    Decimal('5')
    
    >>> remove_exponent(Decimal('5.500'))
    Decimal('5.5')
    
    >>> remove_exponent(Decimal('5E+3'))
    Decimal('5000')
    

提交回复
热议问题