I've got a python Decimal (a currency amount) which I want to round to two decimal places. I tried doing this using the regular round() function. Unfortunately, this returns a float, which makes it unreliable to continue with:
>>> from decimal import Decimal
>>> a = Decimal('1.23456789')
>>> type(round(a, 2))
<type 'float'>
in the decimal module, I see a couple things in relation to rounding:
I think that none of these actually give what I want though (or am I wrong here?).
So my question: does anybody know how I can reliably round a Python Decimal to 2 decimal places so that I have a Decimal to continue with? All tips are welcome!
Since Python 3.3 you can use round()
with a Decimal
and it will return you a Decimal
:
>>> from decimal import Decimal
>>> round(Decimal('3.14159265359'), 3)
Decimal('3.142')
See details in this answer.