1

Helo everyone.

int[] ai1=new int[2] { 3514,3515 };

    void average1()
    {
        List<int> aveList = new List<int> { ai1[0],ai1[1]};
        double AveragLI = aveList.Average();
        int AverLI = (int)Math.Round((double)AveragLI);
        label1.Text = AverLI.ToString();
    }

Returns 3514; should not be 3515?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
Ocaccy Pontes
  • 257
  • 1
  • 5
  • 14
  • possible duplicate of [Why does Math.Round(2.5) return 2 instead of 3 in C#?](http://stackoverflow.com/questions/977796/why-does-math-round2-5-return-2-instead-of-3-in-c) – Nickolay May 04 '13 at 12:59

2 Answers2

3

Math.Round is the culprit

int AverLI = (int)Math.Round((double)AveragLI);

Its what we call Banker's Rounding or even rounding.

Info on Math.Round says

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.

3514.5 is rounded to 3514 and 3515.5 will also be rounded to 3514.

Read this

To avoid do this

int AverLI = (int)Math.Ceiling((double)AveragLI);
Community
  • 1
  • 1
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • It's the other way around, banker's rounding [rounds to even, not odd as you state](http://en.wikipedia.org/wiki/Rounding#Round_half_to_even) – fvu May 04 '13 at 01:32
  • Note that `Math.Ceiling(3514.1) == 3515`. This may or may not be what you need; it's not quite the same as rounding. – Tim S. May 04 '13 at 01:50
  • Isn't `Math.Round(3515.5) == 3516`? Because the nearer even number is 3516 – Fendy May 04 '13 at 05:49
2

The default rounding scheme for Math.Round is what's known as banker's rounding (which is the standard in financial and statistical areas), where midpoint values are rounded to the nearest even number. It looks like you were expecting midpoint values to be rounded away from zero (which is the kind you were probably taught in grade school: if it ends in 5, round up).

If you were just concerned that it wasn't working in an acceptable way, don't worry. If you'd like it to be rounded away from zero, you can do this:

int AverLI = (int)Math.Round((double)AveragLI, MidpointRounding.AwayFromZero);
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • but rounding 3514.1 your way also returns 3514. even though it should round away from zero i.e. it should give 3515. – Nikhil Agrawal May 04 '13 at 01:59
  • @NikhilAgrawal No, the `AwayFromZero` value only changes what happens at the midpoint (hence `MidpointRounding`), e.g. at 3514.5 it goes away from zero to 3515, but 3514.1 rounds to the nearest integer, 3514. – Tim S. May 04 '13 at 12:35