Question

I have created an accreditation system where a user can take exams. On marking the exam i wish to return a percentage figure. So i am taking the correct questions figure, dividing it by the number of questions in the exam and multiplying it by 100.

My issue is rounding the number up. So if the figure returned was 76.9 my code is giving me 76 where rounded up it should be 77 etc.

this is the line of code i that is working this out...

int userScorePercentageConvert = (int)decimal.Round((correctQuestionsForAttempt.Count / dvAttemptQuestions.Count * 100), MidpointRounding.AwayFromZero);

Can anyone tell me how to amend this piece of code so it is rounding correctly

i.e. 43.4 = 44 | 67.7 = 68 | 21.5 = 22

Many thanks in advance.

Was it helpful?

Solution

The problem is that you're using integer division right here:

(correctQuestionsForAttempt.Count / dvAttemptQuestions.Count * 100)

With integer division in a case like this, you'll always end up with 0 or 100.

This will work:

(100.0 * correctQuestionsForAttempt.Count / dvAttemptQuestions.Count)

Also, from what you describe, you want a Ceiling function (think of it as rounding up), not a Round (rounding to the nearest integer, with options on how to round midpoint values).

int userScorePercentageConvert = (int)Math.Ceiling(100.0 * correctQuestionsForAttempt.Count / dvAttemptQuestions.Count);

OTHER TIPS

I believe you are looking for Math.Ceiling

decimal number = 43.4M;
int roundedNumber = (int) Math.Ceiling(number);

That will give you 44

You can simply do Math.Ceiling(43.4)

Just add .5 to your number before casting it

This isn't a rounding issue; it's a number type issue.

The .Count property of a collection (I'm assuming that's what correctQuestionsForAttempt and dvAttemptQuestions are) is an int. Dividing an int by an int will give you another int, without any decimal places. Truncating the decimal likes this gives the appearance of rounding down. The result is that your call to decimal.Round is trying to round something that is already an integer.

If you multiple the number correct by 100 before you divide by the total, this issue should be corrected.

You want Math.Ceiling() - see here.

In your context, it would be used as follows:

int userScorePercentageConvert = (int)Math.Ceiling((correctQuestionsForAttempt.Count / dvAttemptQuestions.Count * 100));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top