Steve Rogers
Steve Rogers

Reputation: 1123

Calculating Percentage in C#

What am I missing here while attempting to calculate the percentage complete? My percentage equation seems to return an incorrect percentage.

Int32 counter = 0;

foreach (var vehicle in vehicles)
{
    counter += 1;

    Int32 percentage = (Int32)((double)counter * vehicles.Count()) / 100;

    _worker.ReportProgress(percentage);


    if (_worker.CancellationPending)
    {
        e.Cancel = true;
        _worker.ReportProgress(0);
        return;
    }
}

Upvotes: 4

Views: 21222

Answers (4)

Sogger
Sogger

Reputation: 16122

You can also use Math.round():

Int32 percentage = (Int32)Math.Round( (double)(counter * 100) / vehicles.Count());

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

Try this :-

  int percentage= (int)( ((100f * counter) / vehicles.count()));

Cast to float to avoid integer division giving you a zero, and you can add 0.5 for integer rounding. Use 0.5f not 0.5 to keep it from expanding to double ie

  int percentage= (int)(0.5f + ((100f * counter) / vehicles.count()));

Upvotes: 3

Justin
Justin

Reputation: 86729

To work out percentages you should be doing

progress
--------  x 100
 total

You are doing

progress x total
----------------
       100

Try using (counter * 100) / vehicles.Count() instead.

Note: If you do the multiplication by 100 before the division it means you don't need to mess about with casts to floats / doubles, however it does mean that all of your percentages are rounded down. If you want a more precise percentage then cast to doubles and don't worry about the order.

Upvotes: 12

user287107
user287107

Reputation: 9417

how about

     Int32 percentage = counter * 100 / vehicles.Count();

Upvotes: 9

Related Questions