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:
- ROUND_05UP
- ROUND_CEILING
- ROUND_DOWN
- ROUND_FLOOR
- ROUND_HALF_DOWN
- ROUND_HALF_EVEN
- ROUND_HALF_UP
- ROUND_UP
- Rounded
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!
decimal.getcontext().prec=2
. – Interstate12345678
into1.2E+7
, but only after doing calculations on it, not right after definition). – Carobround
does return aDecimal
instance directly with Python 3; it's only on Python 2 that it converts tofloat
. Even then, though, you'll still needquantize
if you want anything other than the defaultROUND_HALF_EVEN
rounding mode. – Boise