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

Mark Dickinson dickinsm at gmail.com
Mon Mar 23 05:44:23 EDT 2009


On Mar 23, 6:40 am, valpa <valpass... at gmail.com> wrote:
> I only need the 3 digits after '.'
>
> Is there any way other than converting from/to string?

And in Python 3.0, just use the built-in round function:

>>> from decimal import Decimal
>>> round(Decimal('1.23456789'), 3)
Decimal('1.235')

This uses the rounding specified by the context, so if
you want a rounding mode other than the default
ROUND_HALF_EVEN, just set the context rounding
appropriately:

>>> from decimal import getcontext, ROUND_DOWN
>>> getcontext().rounding = ROUND_DOWN
>>> round(Decimal('1.23456789'), 3)
Decimal('1.234')

Mark



More information about the Python-list mailing list