Bro*_*bay 4 python currency decimal rounding
我似乎无法理解十进制文档使用十进制类获得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
Run Code Online (Sandbox Code Playgroud)
那应该是2.78,但我一直得到2.77.
编辑:测试python 3.4
如果您在代码中添加一行:
print (decimal.Decimal(2.775))
Run Code Online (Sandbox Code Playgroud)
然后你会明白为什么它会四舍五入:
2.774999999999999911182158029987476766109466552734375
Run Code Online (Sandbox Code Playgroud)
的值2.775作为文字,被存储为双重,这限制了精度.
如果您将其指定为字符串,则将更准确地保留该值:
>>> import decimal
>>> print (decimal.Decimal(2.775))
2.774999999999999911182158029987476766109466552734375
>>> print (decimal.Decimal('2.775'))
2.775
Run Code Online (Sandbox Code Playgroud)