Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round Python Decimal instance

How do I round a Python Decimal instance to a specific number of digits while rounding to the nearest decimal?

I've tried using the .quantize(Decimal('.01')) method outlined in the docs, and suggested in previous answers, but it doesn't seem to round correctly despite trying different ROUND_ options. I've also tried setting getcontext().prec, but that seems to only control the total number of digits in the entire number, not just the decimals.

e.g. I'm trying to do something like:

assert Decimal('3.605').round(2) == Decimal('3.61')
assert Decimal('29342398479823.605').round(2) == Decimal('29342398479823.61')
assert Decimal('3.604').round(2) == Decimal('3.60')
assert Decimal('3.606').round(2) == Decimal('3.61')
like image 737
Cerin Avatar asked Apr 05 '13 02:04

Cerin


People also ask

How do you round to 2 decimal places in Python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.

How do you round off 0.5 in Python?

Call the math. floor() method passing it the number multiplied by 2 . Divide the result by 2 . The result of the calculation is the number rounded down to the nearest 0.5 .


1 Answers

I think you need to use the decimal.ROUND_HALF_UP option to quantize to get what you want.

>>> for x in ('3.605', '29342398479823.605', '3.604', '3.606'):
    print x, repr(Decimal(x).quantize(Decimal('.01'), decimal.ROUND_HALF_UP))

3.605 Decimal('3.61')
29342398479823.605 Decimal('29342398479823.61')
3.604 Decimal('3.60')
3.606 Decimal('3.61')
like image 154
Mark Ransom Avatar answered Oct 02 '22 02:10

Mark Ransom