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

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Mar 23 03:24:26 EDT 2009


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, 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)



-- 
Steven



More information about the Python-list mailing list