简体   繁体   English

Python ROUND_HALF_UP 未按预期工作

[英]Python ROUND_HALF_UP not working as expected

I can't seem to understand the decimal docs to get 2.775 to round to 2.78 using the decimal class.我似乎无法理解使用十进制类将 2.775 舍入到 2.78 的十进制文档。

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

That SHOULD round to 2.78, but I keep getting 2.77.这应该四舍五入到 2.78,但我一直得到 2.77。

EDIT: Testing on python 3.4编辑:在 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

The value 2.775 , as a literal is stored as a double, which has limited precision.2.775作为文字存储为精度有限的精度值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM