在打印函数中将浮点格式四舍五入为两位小数

2024-09-28 21:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

print ("Cost: %f per %s" % (mrate[choice], munit[choice]))

输出:

Cost: 25.770000 per 10gm tube

我怎样才能在打印时把它四舍五入到两位小数,这样我就可以得到25.77的输出


Tags: 代码printcostchoice小数pertubemunit
3条回答
>>> print ("Cost: %f" % 25.77)
Cost: 25.770000
>>> print ("Cost: %.2f" % 25.77)
Cost: 25.77

不确定在PyDoc中到底在哪里找到它,但至少可以找到相同的宽度精度规则here

您需要在print函数中使用如下格式规范:

value = 25.7700000001
print("%.2f" % (value))

如果您使用%.2f,您将得到两个小数位,例如:

测试代码:

value = 25.7700000001
print("%f %.2f" % (value, value))

结果:

25.770000 25.77

相关问题 更多 >