Python ROUND_HALF_UP无法正常工作 [英] Python ROUND_HALF_UP not working as expected
本文介绍了Python ROUND_HALF_UP无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎无法理解十进制文档,使用十进制类将2.775舍入为2.78。
I can't seem to understand the decimal docs to get 2.775 to round to 2.78 using the decimal class.
import decimal
decimal.getcontext().prec = 7
print(decimal.Decimal(2.775).quantize(
decimal.Decimal('0.00'),
rounding=decimal.ROUND_HALF_UP
))
>> 2.77 # I'm expecting 2.78
该值应该取整为2.78,但我一直得到2.77。
That SHOULD round to 2.78, but I keep getting 2.77.
编辑:
在python 3.4上进行测试
Testing on python 3.4
推荐答案
如果在代码中添加一行,这样:
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
值 2.775
,因为字面量存储为精度有限的 double 。
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
这篇关于Python ROUND_HALF_UP无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文