Python Round off function problem

Back to General discussions forum

tanay8705     2020-10-09 19:24:56

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.

Rodion (admin)     2020-10-09 22:00:46
User avatar

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 :)

Ankan Bera     2021-01-16 19:06:07

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.

Rodion (admin)     2021-01-18 16:14:21
User avatar

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 :)

Ankan Bera     2021-01-29 20:30:40

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
Rodion (admin)     2021-02-01 10:07:27
User avatar

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 :)

Please login and solve 5 problems to be able to post at forum