Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal.Round default setting for MidpointRounding [duplicate]

Tags:

The following applies:

var rounded = Decimal.Round(7.635m, 2); //rounded: 7.63 

This, to me, is wrong and unexpected behavior. I would assume the value of rounded to be 7.64.

To achieve this, I can do:

var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero); //rounded: 7.64 

How can this not be the default behavior of Decimal.Round? Any good reason for this?

like image 570
Erik Kinding Avatar asked Mar 14 '13 09:03

Erik Kinding


People also ask

How do you round to a decimal place in C#?

Round(Decimal, Int32) Method This method is used to round a Decimal value to a specified number of decimal places. Syntax: public static decimal Round (decimal d, int decimals); Parameters: d: It is a decimal number which is to be rounded.

How do you round a double number in C#?

Round(Double, Int32, MidpointRounding) This method is used to rounds a double precision floating-point value to a specified number of fractional digits. A parameter specifies how to round the value if it is midway between two numbers.

How do you round in C sharp?

The Math. Round() method in C# rounds a value to the nearest integer or to the specified number of fractional digits.


1 Answers

How can this not be the default behavior of Decimal.Round? Any good reason for this?

If you look at the documentation of Decimal.Round Method (Decimal)

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called round half to even or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction. It is equivalent to calling the Round(Decimal, MidpointRounding) method with a mode argument of MidpointRounding.ToEven.

like image 183
Habib Avatar answered Sep 21 '22 17:09

Habib