python ROUND_HALF_EVEN 如何工作

Adi*_*tri 1 python math floating-point rounding

round(0.265, 2)即使我的全局上下文“舍入”设置为 ,为什么我的答案还是 0.27 ROUND_HALF_EVEN

这是我的代码。

import decimal
from decimal import Decimal

print(decimal.getcontext())

a = 0.265
print(Decimal(a))
print(round(a, 2)) # current output: 0.27
Run Code Online (Sandbox Code Playgroud)

这是输出

import decimal
from decimal import Decimal

print(decimal.getcontext())

a = 0.265
print(Decimal(a))
print(round(a, 2)) # current output: 0.27
Run Code Online (Sandbox Code Playgroud)

我很困惑,因为我认为输出应该是 0.26 而不是 0.27,因为舍入设置为ROUND_HALF_EVEN

Pau*_*aul 5

0.26500000000000001332267629550187848508358001708984375是 0.265 的二进制近似值,更接近 0.27。

尽量a = Decimal('0.265')保持精度。

来自https://www.programiz.com/python-programming/methods/built-in/round