how to convert from Decimal('1.23456789') to Decimal('1.234')

Mark Dickinson dickinsm at
Mon Mar 23 09:11:00 CET 2009

On Mar 23, 7:01 am, alex23 <wuwe... at> wrote:
> On Mar 23, 4:40 pm, valpa <valpass... at> wrote:
> > I only need the 3 digits after '.'
> > Is there any way other than converting from/to string?
> I'm not sure if this is the canonical way but it works:
> >>> d = Decimal('1.23456789')
> >>> three_places = Decimal('0.001') # or anything that has the exponent depth you want
> >>> d.quantize(three_places, 'ROUND_DOWN')
> Decimal('1.234')

Yes, that's the official 'right way'.  There's
also a _rescale method that does this:

>>> Decimal('1.23456789')._rescale(-3, 'ROUND_HALF_EVEN')

... but as the leading underscore indicates, it's
private and undocumented, so you shouldn't rely on it
not to change or disappear in a future version.

The two methods are subtly different, in that the
quantize method respects the current context, while
the _rescale method ignores it.  For example:

>>> getcontext().prec = 3
>>> Decimal('1.23456789').quantize(Decimal('0.001'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/dickinsm/python_source/trunk/Lib/", line
2364, in quantize
    'quantize result has too many digits for current context')
  File "/Users/dickinsm/python_source/trunk/Lib/", line
3735, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: quantize result has too many digits for
current context
>>> Decimal('1.23456789')._rescale(-3, 'ROUND_DOWN')
[61114 refs]


More information about the Python-list mailing list