Sanity check, using Math.Round to round up to two decimal places

Out of curiosity why does the following test fail? Doesn't Math.Round, round up?

    [Test]
    public void MathRound()
    {
        Assert.AreEqual(7.13, Math.Round(7.125,2));
    }

enter image description here

Jon Skeet
people
quotationmark

From the Round documentation (looking at Round(double, int):

Rounds a double-precision floating-point value to a specified number of fractional digits, and rounds midpoint values to the nearest even number (example).

Your value is exactly 7.125 (there's no lack of precision here) and it is in the midpoint in the value after the digit you're rounding to, so that digit is rounded to even.

If you want a midpoint rounding mode of "round up", you should say so:

Assert.AreEqual(7.13, Math.Round(7.125, 2, MidpointRounding.AwayFromZero));

(You should usually provide a tolerance to Assert.AreEqual when comparing double values anyway, but that's a separate discussion.)

people

See more on this question at Stackoverflow