Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to create a percentage value from two integers in C#?

Tags:

c#

.net

casting

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?

like image 881
Vaccano Avatar asked Jan 23 '10 18:01

Vaccano


People also ask

How do I figure out a percentage of two numbers?

Answer: To find the percentage of a number between two numbers, divide one number with the other and then multiply the result by 100.

How do you find the percentage of an array?

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 .

How can calculate marks percentage?

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.


2 Answers

How about just mappedItems * 100.0 / totalItems and casting this to the appropriate type?

like image 51
John Feminella Avatar answered Oct 01 '22 17:10

John Feminella


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.

like image 30
dragonroot Avatar answered Oct 01 '22 16:10

dragonroot