John's profileJohn BarshingerPhotosBlogLists Tools Help

Blog


    February 20

    Caught sleeping in Math class again...

     

    There are two ways to round a number using the Math.Round method in .NET 2.0:

     

    ·         MidPointRounding.AwayFromZero - When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.

    ·         MidPointRounding.ToEven - When a number is halfway between two others, it is rounded toward the nearest even number. 

     

    MidPointRounding.ToEven is the DEFAULT!

     

    This means that:

     

    Math.Round(4.5) will return 4

    Match.Round(5.5) will return 6

     

    HUH?

     

    My old math -- would expect the following results:

    4.5 -> 5

    5.5 -> 6

     

    In order to get my expected results, the following calls need to be made:

     

    Math.Round(4.5, MidPointRounding.AwayFromZero) will return 5

    Math.Round(5.5, MidPointRounding.AwayFromZero) will return 6

     

    According to the doc, the ToEven is the IEEE standard. I guess I know I am old when rounding no longer works as I would expect, unless I was sleeping during that class...