Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python decimal rounding

Tags:

python

decimal

Opinion #18, in 20 controversial programming opinions

got me thinking. So i tried out printing pi's value to 5 decimal places.

It was okay since I thought I could definitely do it in Python quickly. A few seconds on Google I got to know the Decimal module of Python . And i was done. Rest was basic logic that anyone can come up with to sum up the series to get the value of Pi.

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

i wrote the above quick script just to check what i'm gonna get.

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

>>>3.14286

to be exact.

I want to know how can I make sure that the Nth place after decimal isn't rounded off? I mean here I would have wanted the answer to be 3.14285

like image 394
bad_keypoints Avatar asked Sep 12 '12 05:09

bad_keypoints


People also ask

How do you round decimals in Python?

Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

How do you round to 2 digit decimals in Python?

Use the ceil() function(returns a ceiling value of the number i.e., the smallest integer greater than or equal to the number), to round the number upto the 2 decimal places and print the resultant number.

Does 0.5 round up or down Python?

For <0.5, it rounds down, and for >0.5, it rounds up. For =0.5, the round() function rounds the number off to the nearest even number. So, 0.5 is rounded to zero, and so is -0.5; 33.5 and 34.5 are both rounded off to 34; -33.5 -34.5 are both rounded off to -34, and so on.

Does .2f round Python?

Just use the formatting with %. 2f which gives you round down to 2 decimal points.


1 Answers

Just like you specify precision using the Decimal context you can also specify rounding rules.

from decimal import *

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

print Decimal(22)/Decimal(7)

the result will be

3.14285

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

like image 103
Eduardo Avatar answered Sep 24 '22 06:09

Eduardo