Back to General discussions forum
For question 6 of this series which states to calculate the rounded off quotient of two numbers, the python's round() function rounds off "even-number".5 to the nearest small integer and "odd-number".5 to the nearest large integer i.e. 2.5 is rounded off to 2 but 3.5 is rounded off to 4. Thereby I would like some suggestions on how to deal with this problem.
Hi Friend.
Thereby I would like some suggestions on how to deal with this problem.
There are many ways - either tuning round function or making your own - and internet is bloating with recipes which you'll easily find from Google :)
You can also use search over this site (there should be search box at the top), as this question of course, was asked hundreds of times. Three of them during past couple of days.
Sorry, but for programmer it is crucial to learn how to search for basic information :)
I found it helpful to round it to 2 decimal point , then add .01. then return with Rounding again. it bypasses the problem for 2.5.
Sorry Friend, but while it may seem "helpful" it is not correct :)
round(round(2.4999,2)+.01) #yields 3 instead of 2
You see, what is bad about your approach, is that it is "almost correct" so it would work almost always but will betray you at some subtle case and you will search for such delicate mistake for quite a some time. Such code should be avoided generally.
More "helpful" would be to read the documentation on round
and set preferred rounding mode for example :)
Hi,
Thanks for the heads up, was thinking only according the test cases of the problem. So,python 3 apprently rounds down even numbers with halfway decimal value. I tried the below approach, please let me know of your comments,
if int(result) % 2 == 0:
decimal= result - int(result)
if round(decimal,2) == 0.5:
result= int(result)+1
Sorry Friend, this doesn't look any better.
Why round(decimal, 2)
??? What is so special about 2 digits? I leave it to yourself to find example
which is not rounded correctly by this code :)
As you already solved the problem, browse other's solutions to see shorter approaches. It should be two-line at most. Shorter variant is single-line and works for most languages, not only Python...
So,python 3 apprently rounds down even numbers with halfway decimal value.
Yes, but you can either use types / functions where rounding mode is adjustable - or just not using round
function
at all :)