Python decimal rounding

Opinion No. 18, in 20 controversial programming opinions

made me think. So I tried to print the pi value up to 5 decimal places.

This was normal since I thought I could do it in Python quickly for sure. For a few seconds on Google, I met a Python decimal module . And I'm done. Rest was the basic logic that anyone could think of to summarize the series to get the Pi value.

>>>from decimal import *
>>>getcontext().prec = 6
>>>Decimal(22)/Decimal(7)

I wrote the above quick script to check what I get.

But here's the thing, getcontext().prec = 6gave me a rounded value!

>>>3.14286

to be precise.

, , N- ? , , 3.14285

+5
1

, , Decimal, .

from decimal import *

getcontext().prec = 6 
getcontext().rounding = ROUND_FLOOR

print Decimal(22)/Decimal(7)

3.14285

http://docs.python.org/release/3.1.5/library/decimal.html#decimal.Context

+9

All Articles