0
print("%.2f" %(22.235))
print("%.2f" %(22.225))

>>>22.23
>>>22.23

In the code written above, I rounded 22.235 and 22.225 using '%.2f'

The result I thought was 22.24, 22.23, but both of them were 22.23.

Through Googleing, I learned that Python's rounding rules are different

If the last number is 5, the rule was to make the nearest even number.

But the code I wrote is not following it.

And even when I randomly change the numbers except 5, the rounding value changes irregularly.

I need professional help. Thank you very much.

Craicerjack
  • 6,203
  • 2
  • 31
  • 39
  • 1
    "I need professional help." - Dont we all. ;p – Craicerjack Mar 23 '20 at 19:30
  • I'll correct the wrong sentence. It means that rounding rules change when I modify numbers except 5. – ellemedit Mar 23 '20 at 19:30
  • `math.floor()` and `math.ceil()` might be what you are looking for... Do you want them rounded up or down? – Craicerjack Mar 23 '20 at 19:31
  • The answers to this question might help with regard to python and rounding floating point numbers and why there are issues - https://stackoverflow.com/questions/31818050/round-number-to-nearest-integer – Craicerjack Mar 23 '20 at 19:34
  • @Craicerjack I'm sorry. I know how to use the Math module. I was working on my teaching materials, and I found this error in the process. So I thought I had to know and move on. – ellemedit Mar 23 '20 at 19:35
  • Python uses "bankers rounding", in which the normal (.5 rounds upwards) rule doesn't always work. This in intentional however, and using Decimal class and/or math - library you can select in which way rounding should be done. Edit: read more: https://www.google.com/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior&ved=2ahUKEwjYivXkrLHoAhXF86YKHSmrDFoQFjACegQIBRAB&usg=AOvVaw3vsv16avpWVzqBUmCAjwvJ – JuhaniTakkunen Mar 23 '20 at 19:37
  • Thanks to the term "banker's rounding" which @JuhaniTakkunen mentioned, I found https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior. – AMC Mar 23 '20 at 20:10
  • Does this answer your question? [Python 3.x rounding behavior](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) – AMC Mar 23 '20 at 20:12

0 Answers0