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

慕码人2483693
TA贡献1860条经验 获得超9个赞
('%f' % x).rstrip('0').rstrip('.')
%g
%g

呼唤远方
TA贡献1856条经验 获得超11个赞
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
提交
取消