I ran into an issue with number rounding in C#. At first glance, the Math.Round() method seems to work correctly, but when rounding certain numbers, the results are unexpected.
Example:
- For the number 3.1455543, calling Math.Round(3.1455543, 2) returns the expected result — 3.15.
- However, for the number 3.1447456, the same method Math.Round(3.1447456, 2) returns 3.14, which is not what I expected (I want 3.15).
Can anyone explain why this happens? I understand that the Math.Round method uses “banker’s rounding” (round half to even), but why does this specific case not follow the expected rounding behavior?
Is there a solution to this problem so that numbers round according to standard mathematical rules instead of the “banker’s rounding” method?
3
Bankers rounding would only make a difference when rounding 3.1450000. For your value only the “regular” rules apply: round towards nearest, which is 3.14.
FYI Math.Round(3.1447456, 2, MidpointRounding.ToPositiveInfinity)
does give 3.15, as would any number greater than 3.14 (such as 3.140001) – it’s effectively Math.Ceiling, but with (in this case 2) decimals.
It references the 3rd Number From the nearest 2 Decimal Places.
Math.Round(number, neareast)
number is the number
nearest is the decimal place being rounded
(nearest + 1) is what determines if it rounds up or down
Any (nearest + 1) thats greater than 5 rounds (nearest) up by 1
Jay Evans is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3