When I try to round the result of division 5/2
it should give me 3
.
Problem
But it says 2. It also says 2 even if I only ask to round 2.5
.
The thing is that it works for numbers greater than 2, example:
round(3.5)
gives4
as it should
When I try to round the result of division 5/2
it should give me 3
.
But it says 2. It also says 2 even if I only ask to round 2.5
.
The thing is that it works for numbers greater than 2, example:
round(3.5)
gives 4
as it should
this is called Banker's rounding, it's the correct way of rounding numbers, it's more like mathematical thing.
Here are a few examples to help you grasp the concept of Banker's rounding:
0.5 is equal to 0. Why? Because the nearest even integer is 0. 1.5 equals 2 when rounded up. Why? Because the nearest even integer is 2. 73.5 equals 74 when rounded up. Why? Because the nearest even integer is 74. 74.5 is equivalent to 74. Why? Because the nearest even integer is 74. 75.5 equals 76 when rounded up. Why? Because the nearest even integer is 76. 76.5 equals 76 when rounded down. Why? Because the nearest even integer is 76.
but you can write your own round function as follows:
a = 5 / 2
def round_it(number):
if number % 1 < 0.5:
return int(number - number % 1)
else:
return int(number + (1 - number % 1))
print(round_it(5 / 2))