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!
If you are using Jupyter Notebook, just add the magic function
%precision 2
for 2 decimal and so forth.But if your values are not
float()
type then you might use the following:You could use the
quantize()
method:The first one you tried worked just fine for me.
This has came to my mind:
but I don't know how fast it is.