-1

So I am trying to build a frontend where I assume that users will expect "school rounding", as in rounding up from values >= 5. I am however having difficulties getting a consistent solution that works for an arbitrary number of decimals.

I have looked at a few answers, such as this one, but none of them seemed to provide the solution that I needed.

Take this example:

Num = 33.497536945812804
from decimal import Decimal, getcontext, ROUND_HALF_UP
getcontext().rounding=ROUND_HALF_UP
# doesn't work:
round(Decimal(str(Num)))
>>> 33
# if I round to 1 decimal and round again, it works.
round(Decimal(str(round(Decimal(str(Num)), 1))))
>>> 34

Now I suppose I could write a function that works like what you learn at school, i.e. starts with the last digit and works its way to the decimal point, but that seems awfully inefficient and complicated. Is there really no better way or package for achieving this seemingly trivial outcome?

DataWiz
  • 401
  • 6
  • 14
  • Your school teaches you that rounding 3.4444...49 is 4? I remember that you should only take into account the last significant number when rounding. –  Sep 06 '19 at 15:06
  • It's been a while, so I'm not sure what exactly my school taught me, but that's what most people around me mean when speaking of "rounding". In any case, what would be the last significant number in your definition? – DataWiz Sep 06 '19 at 15:34
  • 1
    It's a long time here too, but I'm positive your `Num` rounded to whole numbers would become 33 (33.497... is clearly less than 33.5, which is the smallest number that is rounded up (as taught in the school) to 34). With three decimals it would be rounded to 33.498 because of the 5 after ...497 – Tom Brunberg Sep 06 '19 at 15:52
  • You can see it either way. Consistently rounding up from half can also interpreted as applying to subsequent digits. I think these are just regional conventions. – DataWiz Sep 06 '19 at 16:36

1 Answers1

1

You can easily round by adding 0.5 to the float and cut the zeros off by casting to int. That is the correct way to round decimals and

>>> Num = 33.497536945812804
>>> int(Num + 0.5)
33

That was the way I learned to round decimals at school. Rounding this way you wont get the floating point rounding errors.

If you want to round to a specific part after comma do:

>>> int(Num*1000 + 0.5)/1000
33.498
Frank
  • 1,959
  • 12
  • 27