I have two integers that I want to divide to get a percentage.
This is what I have right now:
int mappedItems = someList.Count(x => x.Value != null); int totalItems = someList.Count(); (int)(((double)mappedItems /(double) totalItems) * 100)
This gives the right answer. But that is a lot of casting to do something as simple as get a percentage between two numbers.
Is there a better way to do this? Something that does not involve casting?
Answer: To find the percentage of a number between two numbers, divide one number with the other and then multiply the result by 100.
If sum is defined as integer you should calculate x[i] * 100 / sum . The effect is, that if x[i] * 100 is >= sum your result is > 0 too which is not the case otherwise. However decimal points are lost in this case. Try casting both x[i] and sum to float before calculating, e.g., ((float) x[i]/(float) sum)*100 .
To calculate your exam percentage, divide the marks you received by the total score of the exam and multiply by 100. The answer is 96%, indicating that you received 96% of the marks in your session. Divide a number by two to get 50 percent of it. For instance, 32 divided by two equals 16.
How about just mappedItems * 100.0 / totalItems
and casting this to the appropriate type?
The right integer-only way to get percentage with proper rounding is:
int result = ( mappedItems * 200 + totalItems ) / ( totalItems * 2 );
How do we get there? If we do this thing in floating point, it would be Math.Floor( mappedItems * 100.0 / totalItems + 0.5 )
. We need to transform this formula to be integer-only by multiplying and dividing 0.5 by totalItems, then moving 0.5 * totalItems into dividend, and then multiplying both dividend and divisor by 2 to make fractions go away:
mappedItems * 100.0 / totalItems + 0.5 => mappedItems * 100.0 / totalItems + totalItems * 0.5 / totalItems => ( mappedItems * 100.0 + 0.5 * totalItems ) / totalItems => ( mappedItems * 200.0 + totalItems ) / ( totalItems * 2 ).
At this point the formula is integer-only. When we do integer division, we get floored result, so the integer-only result is equivalent to the mentioned floating-point one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With