+ 1

How to manage rounding and decimals?

a = 1.4999999999999999 b = round(a) print(b) 2 c = 1.499999999999999 d = round(c) print(d) 1 -So my question is what is the simplest way to cut down the number of decimal places taken into account and what would be the result? 1 or 2? -Second question: What function of c would make the result of print(d) 2 instead of 1? -Third question: Is there a simple way to always express the bigger number (so that even if it's only 1.14, you get "2")? -Fourth question: Is there a simple way (and what it is) to make up your own rounding system? ...for example let's say that everything above 1.33 is "2" and bellow 1.33 is "1".

31st Oct 2021, 1:45 PM
Jona Žonta
Jona Žonta - avatar
1 Answer
+ 4
1) As described in the documentation linked in your previous question, Python takes into account 17 digits after floating point. That's why a and c are different from each other. https://docs.python.org/3/tutorial/floatingpoint.html 2) We need to understand the rounding algorithm that modern Python uses https://docs.python.org/3/library/functions.html#round 3) "The bigger number"/ "rounding up" is math.ceil ("The smaller number"/ " rounding down" would be math.floor) 4) You could write an function for it. E.g: if (math.ceil(x) - x > 1/3): return math.ceil(x) else: return math.floor(x)
31st Oct 2021, 2:04 PM
Lisa
Lisa - avatar