This code rounds 1.5 (value = 15) to 2 but also rounds 144.5 (value = 1445) to 144. I dont understand why.
count = 0
while value >= 10:
value = round(value / 10, 0)
count += 1
return value * (10 ** count)
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
If two multiples are equally close, rounding is done toward the even choice.
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