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
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.
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.
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.
Just use the formatting with %. 2f which gives you round down to 2 decimal points.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With