Python 十进制总和的奇怪行为

Python Decimal sum strange behavior

这一定是我的错,但我不明白这是怎么回事。 这里的代码具有这种行为

在循环中我们得到值:

type of data[name]['money_receive']
is Vividict

 class Vividict(dict):
    def __missing__(self, key):
       value = self[key] = type(self)()
       return value

所以

data[name]['money_receive'] = Decimal(1659605.00)
money_receive = data[name]['money_receive'] if data[name]['money_receive'] else Decimal(0.0)


column_sum = {'money_receive': Decimal(0.0)}

column_sum["money_receive"] += money_receive
print u"%s Receive %s" % (money_receive, type(money_receive))
print u"%s Receive All %s" % (column_sum["money_receive"], type(column_sum["money_receive"]))

我明白了

1659605.00 Receive <class 'decimal.Decimal'>
1.660E+6 Receive All <class 'decimal.Decimal'>
print "%.2f"%column_sum["money_receive"]
1660000.00

但是我不明白为什么。

decimal 模块根据上下文中要求的精​​度对计算进行舍入。如果更改默认值,则会出现您描述的情况:

>>> import decimal
>>> print '%f' % (decimal.Decimal('1659605.00') + decimal.Decimal('0.0'))
1659605.000000
>>> decimal.getcontext().prec=4
>>> print '%f' % (decimal.Decimal('1659605.00') + decimal.Decimal('0.0'))
1660000.000000
>>> 

您可以创建一个不同的上下文并临时使用它

>>> ctx = decimal.Context(prec=60)
>>> oldctx = decimal.getcontext()
>>> decimal.setcontext(ctx)
>>> print '%f' % (decimal.Decimal('1659605.00') + decimal.Decimal('0.0'))
1659605.000000
>>> decimal.setcontext(oldctx)

或者在 ctx 对象本身中进行计算

>>> print '%f' % ctx.add(decimal.Decimal('1659605.00'), decimal.Decimal('0.0'))
1659605.000000