drop trailing zeros from decimal

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

    Slightly modified version of A-IV's answer

    NOTE that Decimal('0.99999999999999999999999999995').normalize() will round to Decimal('1')

    def trailing(s: str, char="0"):
        return len(s) - len(s.rstrip(char))
    
    def decimal_to_str(value: decimal.Decimal):
        """Convert decimal to str
    
        * Uses exponential notation when there are more than 4 trailing zeros
        * Handles decimal.InvalidOperation
        """
        # to_integral_value() removes decimals
        if value == value.to_integral_value():
            try:
                value = value.quantize(decimal.Decimal(1))
            except decimal.InvalidOperation:
                pass
            uncast = str(value)
            # use exponential notation if there are more that 4 zeros
            return str(value.normalize()) if trailing(uncast) > 4 else uncast
        else:
            # normalize values with decimal places
            return str(value.normalize())
            # or str(value).rstrip('0') if rounding edgecases are a concern
    
    

提交回复
热议问题