我如何取整一个浮点数?

2024-06-16 13:48:16 发布

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

所以我在python中对浮点进行舍入有点困难。

这就是我的输出结果

Here is your receipt:
Coffe £ 1.2
HotChocolate £ 2.0
Latte £ 3.9000000000000004
Cappucino £ 2.2
Cake £ 1.5
Pensioner Yes
Takeout Yes
Total Cost: 11.664000000000001

如何将值四舍五入到2 dp?

我们将非常感谢您的帮助。


Tags: yourhereisyestotal浮点cakecost
2条回答

浮动有一个属性,它们是非精确的,因为机器的架构,python也有它的限制,请尝试打印如下:

print("%.2f" % some_float)

这个问题包含了你需要的一切:

Limiting floats to two decimal points

示例:

>>> x = 11.664000000000001
>>> 
>>> round(x, 2)
11.66
>>> 
>>> '{:0.2f}'.format(x)
'11.66'
>>> 
>>> '%0.2f' % x
'11.66'
>>>

相关问题 更多 >