user2795569 user2795569 - 9 months ago 76
Python Question

Python Rounding Confusion

This code rounds 1.5 (value = 15) to 2 but also rounds 144.5 (value = 1445) to 144. I dont understand why.

def rounders(value):
count = 0
while value >= 10:
value = round(value / 10, 0)
count += 1
return value * (10 ** count)


This is my attempt to solve the codefights challenge "rounders". Below is an explanation of whats being attempted.

Example

For value = 15, the output should be
rounders(value) = 20;

For value = 1234, the output should be
rounders(value) = 1000.

1234 -> 1230 -> 1200 -> 1000.

For value = 1445, the output should be
rounders(value) = 2000.

1445 -> 1450 -> 1500 -> 2000.

Answer Source

This question is very similar to Strange behavior of numpy.round. What is written there about np.round is directly applicable to the builtin round method of python 3. Note that the behaviour of python 2 is different (as described in the post above. Thanks to ShadowRanger for pointing that out.)

Have a look at the documentation of the round method:

If two multiples are equally close, rounding is done toward the even choice.

That is,

round(2.5) == 2
round(3.5) == 4

You can write a rounding method with the intuitive behaviour with a simple if-statement:

def myRound(x):
    r = x % 1
    if r < 0.5:
        return x-r
    else: 
        return x-r+1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download