drop trailing zeros from decimal

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

    There's probably a better way of doing this, but you could use .rstrip('0').rstrip('.') to achieve the result that you want.

    Using your numbers as an example:

    >>> s = str(Decimal('2.5') * 10)
    >>> print s.rstrip('0').rstrip('.') if '.' in s else s
    25
    >>> s = str(Decimal('2.5678') * 1000)
    >>> print s.rstrip('0').rstrip('.') if '.' in s else s
    2567.8
    

    And here's the fix for the problem that gerrit pointed out in the comments:

    >>> s = str(Decimal('1500'))
    >>> print s.rstrip('0').rstrip('.') if '.' in s else s
    1500
    

提交回复
热议问题