Round off to Even

Allan Muturi
2 min readMay 4, 2023
Photo by Thomas T on Unsplash

I was recently joking around with the round function to round off numbers in C# and something weird happened When rounding off even number the number was retained but when rounding off odd numbers the number was rounded of to the next even number

I thought this was a bug or feature 😂 with the language but I also tried it with python and the result was the same. This made me doubt my lifetime of education which I have doubted since high school.

A screen shot of a terminal showing the python shell with round function
Round off function.

After doing research and alot of googling I came to understand that this was not a languange bug but it was setup as so.

Here is the explanation

The question is what to do when you have a number such as 1.85 and you need to round to the tenth’s place (first decimal place). This number is exactly halfway between 1.8 and 1.9. Why should one always round up in such cases? Actually you shouldn’t. If you do this for several numbers and then use them for something else your results will be skewed high. Instead we need a rule that will result in rounding up half the time and rounding down half the time (when you are doing this to lots of results). How should this be handled? It depends on whether the last number you are keeping is even or odd.

When you discard an exact 5 or 5 followed by nothing but zeros two different things can happen to the last digit you KEEP:

1) If the number you are keeping is even you leave it alone and just get rid of the 5 you are throwing away (round down).

2) If the number you are keeping is odd you round it up (to an even number).

The easiest way to remember this is the last digit KEPT is ROUNDED EVEN

I also realized that this has been the default rounding mode for IEEE 754 operations in order to reduce the bias when operating.

I hope that resolved the issue for all who have or will ever try to use the round function.

Be curious always 🎉🎉

You can reach out to me on my twitter or github

--

--

Allan Muturi

Mobile, web developer and a mathematics and computer science graduate who likes to play with both software and hardware.