I'm not seeing the result I expect with Math.Round.
return Math.Round(99.96535789, 2, MidpointRounding.ToEven); // returning 99.97
As I understand MidpointRounding.ToEven, the 5 in the thousandths position should cause the output to be 99.96. Is this not the case?
I even tried this, but it returned 99.97 as well:
return Math.Round(99.96535789 * 100, MidpointRounding.ToEven)/100;
What am I missing?
You're not actually at the midpoint. MidpointRounding.ToEven
indicates that if you had the number 99.965, i.e., 99.96500000[etc.], then you would get 99.96. Since the number you're passing to Math.Round is above this midpoint, it's rounding up.
If you want your number to round down to 99.96, do this:
// this will round 99.965 down to 99.96
return Math.Round(Math.Truncate(99.96535789*1000)/1000, 2, MidpointRounding.ToEven);
And hey, here's a handy little function to do the above for general cases:
// This is meant to be cute;
// I take no responsibility for floating-point errors.
double TruncateThenRound(double value, int digits, MidpointRounding mode) {
double multiplier = Math.Pow(10.0, digits + 1);
double truncated = Math.Truncate(value * multiplier) / multiplier;
return Math.Round(truncated, digits, mode);
}