Issue
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!
Solution
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.
Answered By - ericbn Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.