How do I calculate Percent complete?

  • Thread starter Thread starter Bill
  • Start date Start date
B

Bill

I have two long values that are passed in an event. I would like to
calculate percent complete as an int but am not quite sure how. Do I need to
convert them to doubles and then use the Math class to round the result?
 
With a real you could just do (CompleteItems / TotalItems)*100 to get a
percentage. You could also go (CompleteItems*100 / TotalItems) to get the
same result. But you're working with long variables so the first option
will give you zero since the (CompleteItems / TotalItems) is a fraction
between 0 and 1. But you can use the second option, as long as
CompleteItems * 100 doesn't go over 9,223,372,036,854,775,807. Unless
you're writing a program to calculate Bill Gates net worth, you should be
pretty safe.

So just multiply CompleteItems by 100, then divide by TotalItems.

Michael C.
 
Won't work. You lose your fractional percentage (longcompleted / longtotal)
to rounding, and zero * 100 always equals zero. Use this instead:

int percentcomplete = Convert.ToInt32(longcompleted*100 / longtotal);

That way you don't lose your percentage to rounding.

Michael C.
 
Back
Top