Search code examples
c#backgroundworkerpercentage

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;
    }
}

Solution

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