Formatting floats without trailing zeros

后端 未结 18 1785
再見小時候
再見小時候 2020-11-22 10:03

How can I format a float so that it doesn\'t contain trailing zeros? In other words, I want the resulting string to be as short as possible.

For example:

<         


        
18条回答
  •  余生分开走
    2020-11-22 10:33

    What about trying the easiest and probably most effective approach? The method normalize() removes all the rightmost trailing zeros.

    from decimal import Decimal
    
    print (Decimal('0.001000').normalize())
    # Result: 0.001
    

    Works in Python 2 and Python 3.

    -- Updated --

    The only problem as @BobStein-VisiBone pointed out, is that numbers like 10, 100, 1000... will be displayed in exponential representation. This can be easily fixed using the following function instead:

    from decimal import Decimal
    
    
    def format_float(f):
        d = Decimal(str(f));
        return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
    

提交回复
热议问题