0

My program cannot determine whether to execute Math.Round as a decimal or a double, but I have no idea how to fix this... Here is my code, though the second to last line is what I am concerned with.

 ArrayList topp1 = new ArrayList();
 int toppcount = 0;
 foreach (Control cb in GroupBoxH1T.Controls)
 {
     CheckBox cb1 = cb as CheckBox;
     if (cb1.Checked == true)
     {
          toppcount++;
          topp1.Add(cb1.Text);
     }
  }

  if (cbhwchoice.Checked == false)
  {
      ArrayList topp2 = new ArrayList();
      foreach (Control cb in GroupBoxH2T.Controls)
      {
          CheckBox cb1 = cb as CheckBox;
          if (cb1.Checked == true)
          {
              toppcount++;
              topp2.Add(cb1.Text);
          }
      }

      toppcount = Math.Round((toppcount/2,MidpointRounding.AwayFromZero);
  }
Rob Rodi
  • 3,476
  • 20
  • 19
Wilson
  • 8,570
  • 20
  • 66
  • 101

3 Answers3

7

Math.Round expects a floating point or decimal number because calling it on an integer would have no effect. If you want to call it, pass in a value of that type. To do so, you can simply cast the numerator and denominator to the desired type. For Example:

decimal value = Convert.ToDecimal(toppcount) / 2.0M;
toppcount = Math.Round(value, MidpointRounding.AwayFromZero);
Rob Rodi
  • 3,476
  • 20
  • 19
  • 1
    You can shorten it by much if you just do: `toppcount = Math.Round(toppcount / 2m, MidpointRound.AwayFromZero);`. The `2m` causes all the necessary casts. – SimpleVar May 13 '12 at 04:32
1

In the second last line

 toppcount = Math.Round((toppcount/2,MidpointRounding.AwayFromZero);

toppcount is integer
2 is also integer
so toppcount/2 will give you integer
as example 1/2 will give you 0

try Convert.ToDecimal(toppcount)/2.0 or (Decimal)toppcount/2.0

bitoshi.n
  • 2,278
  • 1
  • 16
  • 16
0

Replace integer 2 with decimal 2.0 in last statement of the if block. So the statement will become like this:

toppcount = Math.Round((toppcount/2.0))
Shah Aadil
  • 340
  • 1
  • 12
  • Dear NatNgs because the answer from bitoshi.n is talking about explicit conversion. I also faced same problem. I got idea from the bitoshi.n's answer. So i thought of putting it simple so that others get more clear idea. – Shah Aadil Aug 25 '17 at 21:51