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

Mark Dickinson dickinsm at gmail.com
Mon Mar 23 04:11:00 EDT 2009


On Mar 23, 7:01 am, alex23 <wuwe... at gmail.com> wrote:
> On Mar 23, 4:40 pm, valpa <valpass... at gmail.com> 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')
Decimal('1.235')

... 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/decimal.py", line
2364, in quantize
    'quantize result has too many digits for current context')
  File "/Users/dickinsm/python_source/trunk/Lib/decimal.py", 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')
Decimal('1.234')
[61114 refs]

Mark



More information about the Python-list mailing list