-3

I'm new to Python and at the moment I'm writing a code. I need to round up some numbers after I have divided them like this.

n = 5
print(round(n/2))

Why is this showing 2 and not 3? It works on 7 and gives 4 but then on 9 it also gives 4 and not 5. What is wrong here?

Thanks in advance for the help!

ClearWhey
  • 3
  • 2
  • 1
    What version of python are you running? – sphennings Nov 25 '20 at 01:39
  • I'm using version 3.9 – ClearWhey Nov 25 '20 at 01:41
  • https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior – ombk Nov 25 '20 at 01:41
  • 2
    Does this answer your question? [Python 3.x rounding behavior](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) – ombk Nov 25 '20 at 01:41
  • 2
    It's always worth peeking [at the docs](https://docs.python.org/3/library/functions.html#round) occasionally. "if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)" – Mark Nov 25 '20 at 01:42

2 Answers2

1

In python any number ending in .5 is rounded to the nearest even number. So 2.5 is rounded to 2, 3.5 is rounded to 4, and 4.5 is rounded to 4 per the numbers listed in your question.

triedit
  • 169
  • 1
  • 9
  • Alright, I thought it rounded like you normally do in math. Do you know which command I use for it to round up/down normally like you do in math? – ClearWhey Nov 25 '20 at 01:50
  • Use math.ceil() to round up. – triedit Nov 25 '20 at 01:53
  • Yeah but then it always rounds up even if it's like 3.2 – ClearWhey Nov 25 '20 at 01:54
  • Just a note, python doesn't function like normal math so you will have to create a special case using the decimal module. Here's more info: https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python – triedit Nov 25 '20 at 02:02
0

Rounding to Even (Banker’s Rounding)

In Python, if the fractional component of the number is halfway between two integers, one of which is even and the other odd, then the even number is returned.

This kind of rounding is called rounding to even (or banker’s rounding).

Reference

Link

ombk
  • 2,036
  • 1
  • 4
  • 16