math - Python Decimal sum strange behavior -


it must mistake, can't understand going on. here code behavior

in cycle value:

type of data[name]['money_receive'] vividict   class vividict(dict):     def __missing__(self, key):        value = self[key] = type(self)()        return value 

so

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 %s" % (column_sum["money_receive"], type(column_sum["money_receive"])) 

i this

1659605.00 receive <class 'decimal.decimal'> 1.660e+6 receive <class 'decimal.decimal'> print "%.2f"%column_sum["money_receive"] 1660000.00 

but don't understand why.

the decimal module rounds calculations based on precision requested in context. if change default, situation describe:

>>> 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 >>>  

you can create different context , use temporarily

>>> 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) 

or math in ctx object itself

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

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -