0
Math.Round(35.035, 2, MidpointRounding.ToEven) // returns: 35.03

The above as I understand it should round the number to two decimal places. The number is halfway between two numbers 35.03 and 35.04.

So I specified round to even so as far as I understand it this means the last decimal place should be even so I was expecting it to round to the nearest even being 35.04.

Could someone please explain to me why it's rounding to an odd on the last decimal place?

dav_i
  • 27,509
  • 17
  • 104
  • 136
user2005657
  • 607
  • 10
  • 20
  • Just read this answer: http://stackoverflow.com/questions/7360432/c-sharp-rounding-midpointrounding-toeven-vs-midpointrounding-awayfromzero – maseal Sep 17 '13 at 10:14
  • http://stackoverflow.com/questions/1423074/rounding-to-even-in-c-sharp – internals-in Sep 17 '13 at 10:14
  • Problem is that you're using *binary* floating point but care about decimal places. You should use `decimal` e.g. `35.035m` in such cases. – CodesInChaos Sep 17 '13 at 11:58

2 Answers2

3

You need to m or M when you are representing decimals otherwise it will lead to approximation errors.

Try Math.Round(35.035m, 2, MidpointRounding.ToEven)

Suffixes for different data types

float f = 1.2f;
double d = 1.2d;
uint u = 2u;
long l = 2L;
ulong ul = 2UL;
decimal m = 2m;
Carbine
  • 7,849
  • 4
  • 30
  • 54
1

Please see, http://msdn.microsoft.com/en-us/library/f5898377.aspx

there you find the following:

Notes to Callers

Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter. This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14. This occurs because internally the method multiplies value by 10digits, and the multiplication operation in this case suffers from a loss of precision.

Using Math.Round with decimal as first value solves the problem, but for the cost of type conversion.

GreenEyedAndy
  • 1,485
  • 1
  • 14
  • 31