Share via


Math.Round - MidpointRounding Enum

I have received some requests to talk about how you can control roundingin Whidbey. So here we go.... :)  

In Everett, the CLR only support one type of rounding. The Math.Round uses Banker's Rounding Algorithm. (This is the algorithm banks use.. thus the name) This algorithm rounds to the near integer, and if there are two nearest integer, it will round to the even one.

i.e.

Math.Round(2.4); //Returns 2.
Math.Round(2.5); //Returns 2.
Math.Round(2.6); //Returns 3.

Math.Round(3.4); //Returns 3.
Math.Round(3.5); //Returns 4.
Math.Round(3.6); //Returns 4.

Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.

More information about this can be found on MSDN.

In Whindbey, we added flexiblity to allow users to specify how they would like to round borderline situations. You can do so by passing in MidpointRounding Enum into Math.Round() functions.

MidpointRounding consist of two members namely:

MidpointRounding.AwayFromZero

// A number is rounded twoards the nearest number that is away from Zero

MidpointRounding.ToEven

// A number is rounded towards the nearest even number

You can find more about MidpointRounding enum in MSDN2.

I want to start answering frequent ask BCL questions on this blog. If you have a particular question, let me know. :)

Comments

  • Anonymous
    March 31, 2006
    "I see stuff like {0,-8:G2} passed in as a format string. What exactly does that do?" -- Very Confused...
  • Anonymous
    September 29, 2006
    Why more kinds?

    http://www.diycalculator.com/popup-m-round.shtml
  • Anonymous
    June 14, 2007
    "I see stuff like {0,-8:G2} passed in as a format string. What exactly does that do?" -- Very Confused