2024-09-28 21:50:30 发布
网友
我有以下代码:
print ("Cost: %f per %s" % (mrate[choice], munit[choice]))
输出:
Cost: 25.770000 per 10gm tube
我怎样才能在打印时把它四舍五入到两位小数,这样我就可以得到25.77的输出
>>> print ("Cost: %f" % 25.77) Cost: 25.770000 >>> print ("Cost: %.2f" % 25.77) Cost: 25.77
不确定在PyDoc中到底在哪里找到它,但至少可以找到相同的宽度精度规则here
您需要在print函数中使用如下格式规范:
print
value = 25.7700000001 print("%.2f" % (value))
如果您使用%.2f,您将得到两个小数位,例如:
%.2f
value = 25.7700000001 print("%f %.2f" % (value, value))
25.770000 25.77
不确定在PyDoc中到底在哪里找到它,但至少可以找到相同的宽度精度规则here
您需要在
print
函数中使用如下格式规范:如果您使用
%.2f
,您将得到两个小数位,例如:测试代码:
结果:
相关问题 更多 >
编程相关推荐