0

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) gives 4 as it should

enter image description here

hc_dev
  • 8,389
  • 1
  • 26
  • 38
SAM
  • 1
  • 1
  • 4
    Don't make us click on links to see the problem. Post the code, and all the output and error messages, in the question as plain text. – John Gordon Dec 23 '22 at 17:15
  • 3
    It's complicated. Please read: https://docs.python.org/3/library/functions.html#round – DarkKnight Dec 23 '22 at 17:15
  • 2
    It isn't true that it works for all numbers greater than 5. If you evaluate `[n for n in range(1,100,2) if round(n/2) == int(n/2)]` you will see that 50% of the time the number is rounded down and 50% of the time it is rounded up. – John Coleman Dec 23 '22 at 17:22
  • 1
    Welcome SAM, please read [ask] and post your code as [example]. Then we can help you also with other issues. Also do required research [here on SO](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior), and lookup the docs for your Python (version 3.x) [`round()` function](https://docs.python.org/3/library/functions.html?highlight=round#round) first! – hc_dev Dec 23 '22 at 17:29
  • 1
    Does this answer your question? [Python 3.x rounding behavior](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) – hc_dev Dec 23 '22 at 17:37
  • I suppose your question is only about numbers ending in `.5`? If not, then I'd like to mention the existence of functions floor and ceil (in module `math`) – user19513069 Dec 23 '22 at 18:18
  • this is what Iw as looking for thanks! – SAM Dec 23 '22 at 19:00

1 Answers1

0

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))
Ali
  • 49
  • 7