-1


Similar question, but without double and 3 decimal places.
The difference is that the average of two integers we may have a double as a result, but when we use (int) Math.Ceiling ((double) value), result an integer. C# - (int)Math.Round((double)(3514 + 3515)/2) =3514?

But in this case, we have two doubles and

Math.Round(((4.006+4.007)/2),3); // returns 4.006 

Math.Round(((4.008+4.007)/2),3); // returns 4.008 

WHY?

Community
  • 1
  • 1
Ocaccy Pontes
  • 257
  • 1
  • 5
  • 14
  • The answer to the question you linked pretty much sums it up. `Math.Round` rounds to the closest **even** number, not to the closest number. – zneak Nov 23 '13 at 06:40
  • Rounding towards an even last digit is common practice. Did you explore the other rounding options, with the `Math.Round()` overloads? – John Alexiou Nov 23 '13 at 06:42
  • Yes, I need to average two doubles ((x.xxx + y.yyy)/2), both with 3 decimal places. When a double is even (x.xx(even)) and the other odd (y.yy(odd)), we will have as a result a double with 4 decimal places and the fourth digit is 5 (w.www5). So I need to round this double to 3 decimal places. – Ocaccy Pontes Nov 23 '13 at 14:07
  • 1) use `decimal`, not `double`. double can't represent numbers like that exactly, leading to unexpected rounding behaviour. This includes adding an `m` suffix to literals 2) When the value is exactly in the middle, `Round` rounds to the nearest even value by default. Pass in `MidpointRounding.AwayFromZero` if you want to round up on `0.5` – CodesInChaos Nov 24 '13 at 13:15
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Nov 25 '13 at 00:30

1 Answers1

1

From the MSDN:

Return Value

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

Remarks

The behavior of this method follows IEEE Standard 754, section 4. 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.

Also check this related thread

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331