-1
Decimal a = Decimal.Round((Decimal)3.5 * (Decimal)0.01,2);
MessageBox.Show(a.ToString());
a = Decimal.Round((Decimal)4.5 * (Decimal)0.01,2);
MessageBox.Show(a.ToString());

a = Decimal.Round(Decimal.Multiply((Decimal)3.5, (Decimal)0.01), 2);
MessageBox.Show(a.ToString());
a = Decimal.Round(Decimal.Multiply((Decimal)4.5, (Decimal)0.01), 2);
MessageBox.Show(a.ToString());

Why are all the message boxes showing 0.04 when the inputs are different?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Tan
  • 47
  • 7
  • It's not exactly the same as the duplicate, but it's essentially [the same](https://learn.microsoft.com/en-us/dotnet/api/system.decimal.round?view=netframework-4.7.2#System_Decimal_Round_System_Decimal_System_MidpointRounding_) as with `Math.Round`. – ProgrammingLlama Oct 12 '18 at 07:01
  • FYI - instead of `(Decimal)4.5` - its easier to write `4.5M` or `4.5m` - https://stackoverflow.com/questions/3569695/c-sharp-numeric-suffixes – Rand Random Oct 12 '18 at 07:25

2 Answers2

4

This is the expected behavior. As the default MidpointRounding mode is ToEven, both 0.035 and 0.045 are rounded to 0.04.

Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
1

Bacause it uses bankers rounding:

two nearest integers are rounded to the nearest even integer

Specify Round rules:

Decimal.Round((Decimal)4.5 * (Decimal)0.01, 2, MidpointRounding.AwayFromZero)

From the following post:

Statistically half of a sample of numbers are rounded up and half are rounded down

This is how money are rounded to compensate summation error in financial balance computations.

Access Denied
  • 8,723
  • 4
  • 42
  • 72