Python Decimal.Decimal - getcontext().prec 设置和输出中的小数位数

Eri*_*zzz 2 python floating-point precision decimal rounding

我想使用decimal.Decimal 对转换后的数字字符串进行算术运算。我希望返回值有两位小数,无论转换后的数字字符串有多少位小数。

在这种特殊情况下,为什么两位小数精度给我一位小数返回,为什么三位小数精度给我想要的返回(2 位小数 -> 2.15)

from decimal import *
getcontext().prec = 2
a = Decimal(x.replace(',','.'))
b = Decimal(y.replace(',','.'))
print(a), print(b), print(a-b)
>>> 2.60 0.45 2.2

getcontext().prec = 3
a = Decimal(x.replace(',','.'))
b = Decimal(y.replace(',','.'))
print(a, b, a-b)
>>> 2.60 0.45 2.15
Run Code Online (Sandbox Code Playgroud)

小智 7

设置Decimalgetcontext().prec lib 用于返回任何计算数字的数字精度,即 prec = 2 将返回 2 位数字(first=2,second=2),在 prec = 3 中将显示三个数字(first=2 ,第二个=1,第三个=5)。

然而,这里有一个技巧。当您创建 a 和 b 变量时,Decimal 使用您赋予它的数字中的位数作为精度。您可以看到,只需在 IDLE 中调用 a 或 b 即可。