As I understand, the default rounding mode in .NET is "Bankers Rounding", which follows these rules:
- If the digit to round by is less than 5, then round down.
- If the digit to round by is equal to 5 then round to the nearest even number.
- if the digit to round by is greater than 5 then round up.
We can demonstrate this with the following example:
double[] values = {1.14, 1.15, 1.16, 1.24, 1.25, 1.26};
foreach (double value in values)
{
Console.WriteLine(Math.Round(value, 1));
}
// 1.1 (1.14: round down)
// 1.2 (1.15: round to even)
// 1.2 (1.16: round up)
// 1.2 (1.24: round down)
// 1.2 (1.25: round to even)
// 1.3 (1.26: round up)
Then I tried this:
double value = 1.23456;
Console.WriteLine(Math.Round(value, 3));
// 1.235
My expectation was that this would result in 1.234
by the following logic:
1.234
is even- The number to round by is
5
, therefore it should round towards even.
So, why does this produce 1.235
?
CodePudding user response:
I think your misunderstanding is where you say "If the digit to round by is..." when it's really all the digits, all the quantity after that which is being rounded.
In 1.23456
you are rounding .00056
which is greater than 0.0005
so it rounds up.
Banker's rounding only applies at exactly the halfway, to break the tie. Round 1.23350
or 1.23450
to three places and they will both go to 1.234
.