Formatting floats without trailing zeros

后端 未结 18 1566
再見小時候
再見小時候 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:45

    You could use %g to achieve this:

    '%g'%(3.140)
    

    or, for Python 2.6 or better:

    '{0:g}'.format(3.140)
    

    From the docs for format: g causes (among other things)

    insignificant trailing zeros [to be] removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

提交回复
热议问题