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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Mar 23 06:48:24 EDT 2009


On Mon, 23 Mar 2009 01:45:53 -0700, Mensanator wrote:

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

Well, that's hardly any less ugly.

And it also gives different results to my function: my function rounds to 
<places> decimal places, yours to <i> digits. Very different things.


-- 
Steven



More information about the Python-list mailing list