Is there a way to know whether something was rounded up or down in python?

Viewed 439

I basically want to know whether the result of my equation (which is a simple one like this x / y) was rounded up or down. The reason is that I have two simple statements after the rounding line like this:

if h % 2 != 0: h = h + 1
if h % 4 != 0: h = h + 2

and based on the direction of the rounding I would choose the + or - operator, so if the result was rounded up and h % 2 != 0 then it would be h = h + 1 and if it was rounded down then h = h - 1.

Does round() give that kind of information?

Also, is my math correct? (I want the result to be dividable by 4)

4 Answers

Using round() if the number after the given decimal is:

  • >=5 that + 1 will be added to the final value.
  • <5 that the final value will return as is to the mentioned decimals.

But you can use ceil or floor from the math package where it always rounds up or down, respectively.

import math

>>> math.ceil(5.2)
6
>>> math.floor(5.9)
5

Try this to round to 4 directly :

import math

h = 53.75
rounded = math.round(h / 4) * 4

if (rounded > h):
  print("Rounded up by " + str(rounded - h))
else:
   print("Rounded down by " + str(h - rounded))

Let's say you want to know whether 3.9 and 4.4 were rounded. You can do something like this:

def is_rounded_down(val, ndigits=None):
    return round(val, ndigits) < val

Then you can simply call the function to find out

>>> is_rounded_down(3.9)
False
>>> is_rounded_down(4.4)
True

By default round() doesn't give that information, so you need to check yourself.

For Python 2.X integer division returns an integer and always rounds down.

add@LM1756:~$ python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
>>> print 8/3
2
>>> print type(5/2)
<type 'int'>

For Python 3.X integer division returns a float, and so there is no rounding.

add@LM1756:~$ python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
>>> print(8/3)
2.6666666666666665
>>> type(8/3)
<class 'float'>
>>>
Related