decimal and trunkating

Facundo Batista facundobatista at gmail.com
Thu Jun 2 23:57:40 EDT 2005


On 6/2/05, Peter Hansen <peter at engcorp.com> wrote:


>  >>> d = decimal.Decimal('199.999')
>  >>> decimal.getcontext().rounding = decimal.ROUND_FLOOR
>  >>> d.quantize(decimal.Decimal('1.00'))
> Decimal("199.99")
> 
> -Peter
> 
> (I hope this inspires someone who actually knows what he's doing with
> Decimal to post an improved solution.)

This is the right solution, but take in consideration that normally
you'll use one rounding method and you'll round to always the same
places, so, at the beggining of your program you'll do:

>>> import decimal
>>> decimal.getcontext().rounding = decimal.ROUND_FLOOR
>>> d2 = decimal.Decimal("0.01")

and each time you want to round....

>>> d = decimal.Decimal('199.999')
>>> d.quantize(d2)
Decimal("199.99")

So it's not really that ugly....

.    Facundo

Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/



More information about the Python-list mailing list