You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7使用%f打印为何输出大量小数末尾零?

为什么Python脚本中total变量输出有大量小数点后的零?

为何以下脚本中total变量的输出会出现大量小数点后的零?(已知可通过变通方法得到指定输出,但好奇该输出成因)

脚本代码

prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, }
stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, }
for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    print
total = 0
for iteration in prices:
    total = total+ prices[iteration] * stock[iteration]
print "total price: %f"%total

输出结果

banana
price: 4
stock: 6
apple
price: 2
stock: 0
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
total price: 117.000000 #********* why so many zeros?

这问题其实是字符串格式化规则导致的,和变量本身的数值完全没关系!

你最后打印时用了%f这个格式化占位符,在Python 2.x里它默认会强制输出6位小数——不管你的数值是整数还是带小数的浮点数。哪怕你的total实际计算结果是整数117,用%f格式化后也会自动补全到6位小数,于是就出现了117.000000的结果。

如果想让输出更简洁,你可以换这些格式化方式:

  • 用%g:它会自动去掉末尾多余的零,print "total price: %g"%total 会输出 total price: 117
  • 用%.2f:固定显示2位小数,适合金额类场景,输出117.00
  • 直接用整数格式化符%d:如果能确定计算结果一定是整数,print "total price: %d"%total 也会输出干净的117

补充一下:你的total计算结果确实是整数——46 + 20 +1.532 +315 =24+0+48+45=117,只是格式化时被%f强制加上了6位小数而已,变量本身的数值是完全正常的。

内容的提问来源于stack exchange,提问作者zelek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:38:21