Formatting floats without trailing zeros

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

    If you can live with 3. and 3.0 appearing as "3.0", a very simple approach that right-strips zeros from float representations:

    print("%s"%3.140)
    

    (thanks @ellimilial for pointing out the exceptions)

提交回复
热议问题