Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# easy math function

Tags:

c#

I`m trying to calculate a percent of successful jobs in total. Code:

int total = valid + invalid;
int percent = (valid / total) * 100;
if (percent == 0)
{
  MessageBox.Show(Convert.ToString(total) + ":" + Convert.ToString(valid));
  break;
}

If all job are successful, the percent is 100%. If one job is bad, percent is 0 and i get messagebox with: 9:8

8/9*100 = 88.888, not 0.

int percent = Convert.ToInt32((valid / total) * 100);

gives no result. Please, help me. I am Russian, so sorry for bad English.

like image 449
kopaty4 Avatar asked Jun 20 '26 14:06

kopaty4


1 Answers

I'm guessing both valid and invalid are defined as ints. In that case, the result of all calculations will be ints as well.

You either need to cast one of the values to floating point type in the operation or, and this would probably be easier, define one of the values as a floating point type to begin with:

double total = valid + invalid;
int percent = (valid / total) * 100;
like image 122
Justin Niessner Avatar answered Jun 22 '26 04:06

Justin Niessner