[Tutor] Precision with Decimal

Sander Sweers sander.sweers at gmail.com
Sun Feb 1 14:04:43 CET 2009


On Sun, Feb 1, 2009 at 04:05,  <gslindstrom at gmail.com> wrote:
> "The decimal module incorporates a notion of significant places so that 1.30
> + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is
> the customary presentation for monetary applications."
>
> But I get:
>>>> from decimal import Decimal
>>>> a = Decimal('1.25')
>>>> a
> Decimal('1.25')
>>>> b = Decimal('2.50')
>>>> b
> Decimal('2.50')
>>>> a+b
> Decimal('3.8')
>
> I expect (and would like) a+b to be '3.75'. I've read through the
> getcontext() section but must be missing something. Can you help?

You probably set the precision to 2 via getcontext.

example:

>>> import decimal
>>> a = decimal.Decimal('1.25')
>>> b = decimal.Decimal('2.50')
>>> a + b
Decimal("3.75")
>>> decimal.getcontext().prec = 2
>>> a + b
Decimal("3.8")

Greets
Sander


More information about the Tutor mailing list