在Python中格式化浮点数而不尾随零如何格式化浮点数,使其不包含尾随零?换句话说,我希望得到的字符串尽可能短。例如:3 -> "3"3. -> "3"3.0 -> "3"3.1 -> "3.1"3.14 -> "3.14"3.140 -> "3.14"
3 回答

慕丝7291255
TA贡献1859条经验 获得超6个赞
('%f' % x).rstrip('0').rstrip('.')
%g
%g

沧海一幻觉
TA贡献1824条经验 获得超5个赞
from decimal import Decimalprint (Decimal('0.001000').normalize())# Result: 0.001
-更新-
from decimal import Decimaldef format_float(f): d = Decimal(str(f)); return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
添加回答
举报
0/150
提交
取消