Python ROUND_HALF_UP not working as expected

一个人想着一个人 提交于 2019-12-01 19:46:30

If you add a single line to your code thus:

print (decimal.Decimal(2.775))

then you'll see why it's rounding down:

2.774999999999999911182158029987476766109466552734375

The value 2.775, as a literal is stored as a double, which has limited precision.

If you instead specify it as a string, the value will be preserved more accurately:

>>> import decimal

>>> print (decimal.Decimal(2.775))
2.774999999999999911182158029987476766109466552734375

>>> print (decimal.Decimal('2.775'))
2.775
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!