How do I calculate Percent complete?

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?
 
M

Michael C

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.
 
M

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top