Formatting floats without trailing zeros

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

    Here's a solution that worked for me. It's a blend of the solution by PolyMesh and use of the new .format() syntax.

    for num in 3, 3., 3.0, 3.1, 3.14, 3.140:
        print('{0:.2f}'.format(num).rstrip('0').rstrip('.'))
    

    Output:

    3
    3
    3
    3.1
    3.14
    3.14
    

提交回复
热议问题