Alex Rivera | Logout

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

Asked 2010-01-23T18:53:34.903
42

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?

Edit
Report

1 Answer

64

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

answered 2010-01-23T18:55:37.620

Your Answer