Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 748
Steven Rogers Avatar asked Nov 29 '22 02:11

Steven Rogers


2 Answers

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.

like image 86
Justin Avatar answered Dec 05 '22 02:12

Justin


how about

     Int32 percentage = counter * 100 / vehicles.Count();
like image 42
user287107 Avatar answered Dec 05 '22 01:12

user287107