3

Possible Duplicate:
Why does .NET use banker's rounding as default?

Here is a sample code

decimal num1=390, num2=60, result;
result=num1/num2; // here I get 6.5
result=Math.Round(result,0);

the final value of result should be 7 but, I am getting 6. Why such a behavior?

Community
  • 1
  • 1
ajay_whiz
  • 17,573
  • 4
  • 36
  • 44

6 Answers6

6

Check third parameter MidpointRounding.

By default used MidpointRounding.ToEven, so

Math.Round(result,0); // 6.0 
//or
Math.Round(result,0, MidpointRounding.ToEven); // 6.0 

//But:
Math.Round(result,0, MidpointRounding.AwayFromZero); // 7.0 
Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
2

From MSDN:

If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned.

Shurdoof
  • 1,719
  • 13
  • 16
2

This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.

http://msdn.microsoft.com/en-us/library/3s2d3xkk.aspx

Example:

//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
nan
  • 19,595
  • 7
  • 48
  • 80
1

decimal.Math.Round uses MidpointRounding.ToEven as default.

Meaning if the one's digit is odd, it is changed to an even digit. Otherwise, it is left unchanged. This behavior follows IEEE Standard 754, section 4. It is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.

HSBallina
  • 424
  • 4
  • 15
  • Se the doc here: http://msdn.microsoft.com/en-us/library/3s2d3xkk.aspx and here: http://msdn.microsoft.com/en-us/library/ms131274.aspx – HSBallina Dec 17 '10 at 08:47
1

It must be the same reason as why

      Math.Round(6.5, 0);

similarly yields 6 rather than 7. It all comes down to the MSDN documentation link text which exemplify

  Console.WriteLine(Math.Round(3.45, 1)); //Returns 3.4.
  Console.WriteLine(Math.Round(4.35, 1)); // Returns 4.4

in another MDSN Doc is states

The integer nearest parameter d. If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. Note that this method returns a Decimal instead of an integral type.

Carlo V. Dango
  • 13,322
  • 16
  • 71
  • 114
1

Use Math.Ceiling Method(). decimal num1=390, num2=60, result;
result=Math.Ceiling(num1/num2);

Britto Raj
  • 401
  • 1
  • 5
  • 15