0

Let's say that we have a set of decimal values for which we would like to calculate the percentage of the total for each of those values:

decimal [] values = {20.50, 40.25, 70.10, 35.80}; // etc

We also have a total sum of those values:

decimal sum = 166.65;

Now, I would like to have for each of values percentage representation, BUT so that in total, the sum of percents (int) is always equal to 100 as it should be.

Right now I use such formula for calculation of percentage value:

int percent = (int)(Math.Round(values[0] * 100.0m / sum));

but, depending on the input values - because of the rounding, the total SUM of calculated percentages for all of input values is sometimes 99 or 101.

What kind of formula to use to get the most accurate percentage distribution results?

pitersmx
  • 935
  • 8
  • 27
  • What you can do is calculate percentage for all but the last, and for the last take 100 minus the sum of all other percentages. Or else you calculate everything and add or remove 1 to the highest percentage calculated if the sum is 99 or 101. – Rafalon Oct 05 '17 at 12:20
  • Sound like too much processing if you have multiple input values and calculation needs to be done often – pitersmx Oct 05 '17 at 12:22
  • If it should be accurate don't use `int` for `percent`, just use double/decimal – EpicKip Oct 05 '17 at 12:22
  • If you want more precision you have to allow for more decimal places. Otherwise all you can do is attempt to add or remove one percent from one of the results to make the sum work, but then that percentage will actually be less accurate. – juharr Oct 05 '17 at 12:23
  • Oh btw you already answered your own question: `because of the rounding, the total SUM of calculated percentages for all of input values is sometimes 99 or 101.` Then don't round? – EpicKip Oct 05 '17 at 12:24
  • You can't do this in general without reducing the accuracy of the data you display to the user. – Matthew Watson Oct 05 '17 at 12:24
  • @EpicKip thanks for advice, you made my day – pitersmx Oct 05 '17 at 12:28

0 Answers0