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

Mensanator mensanator at aol.com
Mon Mar 23 09:45:53 CET 2009


On Mar 23, 2:24�am, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Sun, 22 Mar 2009 23:40:38 -0700, valpa wrote:
> > I only need the 3 digits after '.'
>
> > Is there any way other than converting from/to string?
>
> You should Read the Fine Manual:
>
> http://docs.python.org/library/decimal.html
>
> [quote]
> The quantize() method rounds a number to a fixed exponent. This method is
> useful for monetary applications that often round results to a fixed
> number of places:
>
> >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
> Decimal('7.32')
> >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
>
> Decimal('8')
>
> [end quote]
>
> In my opinion, that's hideously ugly,

In looking at this for the first time, it struck
me as funny why the first argument to quantize
even requires a number since you can pass a
Conext as an argument. But if you do, precision
is ignored. Quantize isn't the way to do that.

> but you can create a helper
> function very easily:
>
> def round(dec, places, rounding=decimal.ROUND_HALF_UP):
> � � return dec.quantize(decimal.Decimal(str(10**-places)), rounding)

Still ugly. I would do this:

>>> a = Decimal('1.23456789')

>>> for i in xrange(1,6):
	print Context.create_decimal(Context(i,ROUND_DOWN),a)
1
1.2
1.23
1.234
1.2345

>>> print a
1.23456789


>
> --
> Steven




More information about the Python-list mailing list