When specifying the number of decimals, is the behaviour of Math.Round with MidpointRounding.ToEven correct?

StackOverflow https://stackoverflow.com/questions/21901850

I'm trying to use Math.Round however the results I'm getting are not what I expected. I'm finding that it only rounds to even when the following digit is a 5 and cannot have any other digits after that.

Assert.AreEqual<double>(4d, Math.Round(4.5));          // Pass
Assert.AreEqual<double>(5d, Math.Round(4.6));          // Pass
Assert.AreEqual<double>(6d, Math.Round(5.5));          // Pass
Assert.AreEqual<double>(4d, Math.Round(4.500001));     // Fail - 5
Assert.AreEqual<double>(4d, Math.Round(4.45));         // Pass
Assert.AreEqual<double>(4.4, Math.Round(4.45, 1));     // Pass
Assert.AreEqual<double>(4.4, Math.Round(4.450001, 1)); // Fail - 4.5 

The behaviour is also the same for Decimal.Round.

Assert.AreEqual<decimal>(4m, Decimal.Round(4.500001m));      // Fail - 5
Assert.AreEqual<decimal>(4.4m, Decimal.Round(4.450001m, 2)); // Fail - 4.5

Shouldn't rounding only take into account the digit directly following the decimal place you're rounding to, as described in MidpointRounding?

A rounding operation takes an original number with an implicit or specified precision; examines the next digit, which is at that precision plus one; and returns the nearest number with the same precision as the original number.

有帮助吗?

解决方案

The behaviour is correct. You are arguing that 4.50001, 4.51, 4.59, 4.599999999999 should all round down to 4. It is clear that figures over 4.5 are closer to 5 than they are to 4 and therefore should be rounded up to 5.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top