More clarification please on Round method from the Math static Class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

More clarification please on Round method from the Math static Class

I don't understand on how the Round method works especially on how it outputs the following.... Math.Round(6.5) //outputs 6 Math.Round(11.5) //outputs 12 Also Math.Round(6.7) //outputs 7 Math.Round(11.7) //outputs 12 How comes!?

14th Nov 2019, 11:25 AM
Nyandago
Nyandago - avatar
2 Answers
+ 3
Anything that is smaller than X.5 will be rounded to X. Anything that is larger than X.5 will be rounded to X+1. When we hit X.5 exactly, Math.round will round to the nearest even value. That's why we rounded down in your first example and up in the second. It's called banker's rounding and the idea is that if you round often the rounding errors will cancel out this way, and not always round up up up and compound a larger and larger rounding error. You can change the rounding behaviour, see: https://docs.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=netframework-4.8 `ToEven` is the default I described, `AwayFromZero` is what you are maybe more familiar with.
14th Nov 2019, 11:35 AM
Schindlabua
Schindlabua - avatar
+ 4
Thanks so so much Schindlabua , I've now realized that I was confused from ''when we hit X.5 exactly" that was exactly where all the confusion (to me) about Math.Round arose!!
14th Nov 2019, 6:48 PM
Nyandago
Nyandago - avatar