Math.Round for decimal in C #

Possible duplicate:
Why does .NET use banker rounding by 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 the result should be 7 , but I get 6 . Why is this behavior?

+3
source share
6 answers

Check out the third MidpointRounding parameter .

The default is 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 
+6
source

This rounding is sometimes called rounding to the nearest or rounding of the banker. It minimizes rounding errors due to constant rounding of the average value in one direction.

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

:

//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
+2

MSDN:

d , , - , .

+1

decimal.Math.Round MidpointRounding.ToEven .

, , . . IEEE 754, 4. . , - .

+1

,

      Math.Round(6.5, 0);

6, 7. MSDN ,

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

to another MDSN document - these are states

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

+1
source

Use the Math.Ceiling () method. decimal num1 = 390, num2 = 60, result;
Result = Math.Ceiling (num1 / pit2);

+1
source

Source: https://habr.com/ru/post/1780831/


All Articles