1

In Python 3, I'm trying to round the value 4800.5, so I was expecting it to 4801 but it's giving me 4800. I'm not able to track why this is happening. Any help will be appreciated.

3
  • 5
    docs.python.org/3/library/functions.html#round if two multiples are equally close, rounding is done toward the even choice
    – qrsngky
    Commented Jul 14, 2022 at 11:22
  • @qrsngky you should submit that as an answer
    – jkr
    Commented Jul 14, 2022 at 11:25
  • @jakub My comment explains 'why', but I am guessing that the OP wants an alternative that acts like the round of some other languages
    – qrsngky
    Commented Jul 14, 2022 at 11:26

4 Answers 4

3

That's by design.

If you have a look at round function documentation (https://docs.python.org/3/library/functions.html#round) you will find that:

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; 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).

In simple words, 0.5 is a special case which is always rounded toward an even number.

But there're more interesting things. Please have a look at that example:

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.

What you might want to do is to use Decimal for more conventional rounding logic: https://docs.python.org/3/library/decimal.html

For example:

>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_UP)
Decimal('7.33')
0
1

There are lot of ways to round a number. round() behaves according to a particular rounding strategy which may or may not be the one you need for a given situation (see the first comment to your question).

If you want to round your number to the upper, you can try this:

import math

n = 4800.5
print(math.ceil(n))
0
1

you can do something like this:

from decimal import Decimal, ROUND_HALF_UP

def round_half_up(decimal_number, places=0):
    if places == 0:
        exp = Decimal('1')
    else:
        exp_str = '0' * places
        exp_str = exp_str[:-1] + '1'
        exp = Decimal('.{}'.format(exp_str))
    return Decimal(decimal_number).quantize(exp, rounding=ROUND_HALF_UP)


print(round_half_up(4800.5)) -> 4801
print(round_half_up(4800.555, 2)) -> 4800.56
0
-2

Round() function will round up to next value, if decimal is >.5 upto .5 it would round up to just the integer part.

1
  • This is not true. 0.5 will be rounded to the nearest even integer.
    – jkr
    Commented Jul 14, 2022 at 14:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.