0

I am trying to calculate a percentage for first pass yield but divide is not working and is returning a zero

double FirstPassYield = ((RowTotal - DefectCount) / RowTotal) * 100;

I tried individual calculations and they work except when I use divide. I even took to random numbers and divided them and still get a 0. I an not sure way divide keeps returning a 0

Evanark
  • 191
  • 2
  • 4
  • 16
  • Are any of the variables of type `int` by any chance? Try using the search. "Calculation not working" is not a proper problem description and isn't going to yield any results, try "division returns zero". – CodeCaster Dec 17 '14 at 19:50
  • 1
    Also: http://stackoverflow.com/questions/661028/how-can-i-divide-two-integers-to-get-a-double – Justin Niessner Dec 17 '14 at 19:52

1 Answers1

4

Try this instead:

double FirstPassYield = ((RowTotal - DefectCount) / (double)RowTotal) * 100;

When you divide int by int, the result is an int before being cast to a double, so you get zero instead of the value you are expecting. By casting the denominator to a double, the rest of the calculation is cast to match, so you're working with doubles instead of ints before the assign.

danludwig
  • 46,965
  • 25
  • 159
  • 237
Steve Lillis
  • 3,263
  • 5
  • 22
  • 41
  • that works but how do I get my value to output like this 95.20%? I use toString("P") but how to move the decimal? My current output is 9520.55 – Evanark Dec 17 '14 at 20:07
  • Don't multiply by 100. A percentage in C# is on a scale of 0 - 1, not 0 - 100. – Steve Lillis Dec 17 '14 at 20:48