[Python-Dev] Adventures with Decimal

Raymond Hettinger raymond.hettinger at verizon.net
Sat May 21 03:56:28 CEST 2005


> It looks like if you pass in a context, the Decimal constructor still
> ignores that context:
> 
> >>> import decimal as d
> >>> d.getcontext().prec = 4
> >>>
d.Decimal("1.2345678901234567890123456789012345678901234567890000",
> d.getcontext())
> Decimal("1.2345678901234567890123456789012345678901234567890000")
> >>>
> 
> I think this is contrary to what some here have claimed (that you
> could pass an explicit context to cause it to round according to the
> context's precision).

That's not the way it is done.  The context passed to the Decimal
constructor is *only* used to determine what to do with a malformed
string (whether to raise an exception or set a flag.

To create a decimal with a context, use the Context.create_decimal()
method:

>>> import decimal as d
>>> d.getcontext().prec = 4
>>>
d.getcontext().create_decimal("1.234567890123456789012345678901234567890
1234567890000")
Decimal("1.235")



Raymond



More information about the Python-Dev mailing list