B. Clay Shannon B. Clay Shannon - 2 months ago 5
C# Question

Why am I getting 0.0 with this code?

When I enter, in the Windows Calculator utility, "15036/18218*100=" it returns 82.53375782193435

What I really want is 17.47 (100 - 82.53), but that's beside the point at the moment.

With this code:

// Example: thisQty == 3182; totalQty == 18218
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff/totalQty)*100; // this equates to 0.0 for some reason
return string.Format("{0}%", prcntg);
}


...I'm getting 0.0 for the prcntg value. Why? ISTM that this is the same operation that I'm doing by hand in the Calculator utility. Why doesn't it return 82.53375782193435?

Answer

The dividing of 2 ints will be an int even if the correct mathematical answer is with a fraction.

In order to have it keep the decimal part you must divide with a number of a type that holds the fraction part (like double or decimal):

Console.WriteLine(GetPercentage(3182, 18218));

private string GetPercentage(int thisQty, int totalQty)
{
   int diff = totalQty - thisQty; // this equates to 15036
   double prcntg = (diff / (double)totalQty) * 100;
   return string.Format("{0}%", prcntg);
}

BTW - it doesn't matter if you cast to double the diff or the totalQty - for both it will do the / operation returning a double - which means keeping the fraction part

Comments