user1004959
user1004959

Reputation: 627

How to calculate percentages of sum of sub-arrays so that their sum is strictly 100 using C# decimal

Let's say I have an array of integers. Lets logically divide it into just two parts for simplification.

Let's say total sum of all elements of array is 2860800.

Let's say sum of all elements of left half is 2834387.

Let's say sum of all elements of right half is 26413.

Now calculating left half's percentage by 100m * leftHalfSum / totalSum gives 99.07672678970917225950782998.

Similarly, right half's percentage by 100m * rightHalfSum / totalSum is 0.9232732102908277404921700224.

Now, if I add these two percentages in Visual Studio's Watch, it shows me 100. But if I add these in Calculator app in Windows, it gives me 100.0000000000000000000000000024, which is correct.

Basically, I want 100-leftHalfPercentage to be strictly equal to rightHalfPercentage and vice-versa. If I do 100-leftHalfPercentage in Watch, it gives me 0.92327321029082774049217002. Notice that it is exactly the same as rightHalfPercentage but the last two digits 24 are missing.

Thanks.

Upvotes: 4

Views: 661

Answers (2)

Simon Verbeke
Simon Verbeke

Reputation: 3005

Decimals have a maximum precision of 28-29 significant digits (Source). The full result of your calculation would be 30 digits long, to much for a decimal! That's why the last two digits are omitted.

If your result would be larger (a total sum of 10.000 instead of 100 for example) even more digits would be omitted.

The difference is probably caused by something internal and would probably need some inspection of the compiled code by someone more knowledgeable than me.

Upvotes: 2

Guffa
Guffa

Reputation: 700322

The numbers that you have calculated are correct, i.e. they represent their percentages with the same degree of precision.

If you want their sums to be exactly 100, then you have to pick one of the values to be less exact. The value that you choose to sacrifice would simply be calculated by subtracting all the other values from 100.

For example, having three equal groups calculated with one decimals would give you 33.3% for each, giving you a sum of 99.9%. To make the sum 100% you would sacrifice the correctness for one group and calculate it as 100 - 33.3 - 33.3 = 33.4.

Upvotes: 2

Related Questions