将float转换为字符串,在Python中使用小数点后零点切换

Ser*_*ski 9 python string floating-point

我无法通过以下方式将float转换为字符串:

20.02  --> 20.02
20.016 --> 20.02
20.0   --> 20
Run Code Online (Sandbox Code Playgroud)

似乎%g格式是最好的,但我得到奇怪的结果:

In [30]: "%.2g" % 20.03
Out[30]: '20'

In [31]: "%.2g" % 20.1
Out[31]: '20'

In [32]: "%.2g" % 20.3
Out[32]: '20'

In [33]: "%.2g" % 1.2
Out[33]: '1.2'

In [34]: "%.2g" % 1.0
Out[34]: '1'

In [35]: "%.2g" % 2.0
Out[35]: '2'

In [36]: "%.2g" % 2.2
Out[36]: '2.2'

In [37]: "%.2g" % 2.25
Out[37]: '2.2'

In [38]: "%.2g" % 2.26
Out[38]: '2.3'

In [39]: "%.3g" % 2.26
Out[39]: '2.26'

In [40]: "%.3g" % 2.25
Out[40]: '2.25'

In [41]: "%.3g" % 20.02
Out[41]: '20'

In [42]: "%.3g" % 20.016
Out[42]: '20'

In [43]: "%.20g" % 20.016
Out[43]: '20.015999999999998238'
Run Code Online (Sandbox Code Playgroud)

我现在知道的唯一解决方案是检查数字是否为int并且应用%d而不是%f格式化 - 我认为这太复杂了.

有谁知道为什么上面的东西是hapenning?如何以更简单的方式做到这一点?

谢谢.

Den*_*ach 13

使用%f格式说明符:

('%.2f' % (value,)).rstrip('0').rstrip('.')
Run Code Online (Sandbox Code Playgroud)

使用round()功能:

str(round(value)).rstrip('0').rstrip('.')
Run Code Online (Sandbox Code Playgroud)


u0b*_*6ae 6

使用圆形%g - 你想要显示最多2位数,所以圆形到两位数,然后使用%g尽可能短的打印:

>>> "%g" % round(20.016, 2)
'20.02'
>>> "%g" % round(20, 2)
'20'
Run Code Online (Sandbox Code Playgroud)