Search code examples
c#progress-barpercentage

Correct data type for task progress?


I am currently having a problem with programming a simple calculation of a tasks progress in percentages, and i think the problem is that i don't know which data type i should use for it (int, double, decimal, float, ...).

My calculation:

(100 - ((articlesLeft.Count / articleMaximumAmount) * 100))

In the example of my code you can see the calculation for articlesLeft.Count = 52674 and articleMaximumAmount = 53085.

The result in my code always is 100, even though it should be ~0.77 (%) for these values.

Here's my code (i can't post images directly yet)

Which data type should i use, or do i have to do some rounding or formatting of the calculations result, in order to display the correct progress in percentages?


Solution

  • As mentioned in the comments, the reason your calculation fails is that you are doing integer division, so the result will always be zero. To fix this you can do conversion to double

    (100 - ((articlesLeft.Count / (double)articleMaximumAmount) * 100))
    

    or scale the numerator:

    (100 - ((articlesLeft.Count* 100) / (articleMaximumAmount) )
    

    The former will give higher precision if you keep it as a double, while the second alternative will truncate the values to whole percentages.

    I'm not sure what system you are using for reporting progress. When using the built in IProgress your actual progress bar takes an integer value between a configurable min and max values. This gives you a few choices to what type to use in the progress:

    1. The actual number of items processed - Relies on the UI setting the max value of the progress bar to the total number of items.
    2. A percentage integer - Set the maximum to 100 (or 1000, or similar), when reporting you need to scale the value to this range.
    3. A double in 0, 1 range - Needs scaling both when reporting progress value and when updating the progress bar, but has good precision and is fairly easy to work with.

    I'm not personally a fan of representing a percentage value with a double, I find it more natural to just use the proportion, i.e. 0 to 1. If the UI wants to show percentage, permille, or something else, it just have to multiply the value.