Tormod
Tormod

Reputation: 4573

Percentage never to be 100% unless actually 100%

In a report, our client can have more than 100 000 items that are checked and in the report metadata (xml file) want a 2-decimal percentage of how many of the items were "checked OK".

However, the number should not be 100% unless actually everything is ok. Due to the number of items, the standard math operations and String.Format() can do that rounding error.

Is there an elegant solution to this?

The client accepts that 99.99% is a special case that covers 99.999999999% even though it is mathematically incorrect.

The important thing is that the report data does not show 100% when there are items that did not check out ok.

Upvotes: 1

Views: 308

Answers (1)

InBetween
InBetween

Reputation: 32760

What's wrong with a little helper method?

public double GetPercentage(int checkedOk, int total)
{
    if (checkedOk == total)
        return 100.0;

     var percentage = (100.0 * checkedOk) / total;
     return percentage > 99.99 ? 99.99: percentage;
}

I'd remove the magic number ‘99.99` but you get the idea.

Upvotes: 2

Related Questions