Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a number using C# [duplicate]

Tags:

c#

math

rounding

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.

like image 307
Paul Kirkason Avatar asked Dec 04 '22 07:12

Paul Kirkason


2 Answers

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);
like image 184
Tim S. Avatar answered Dec 31 '22 09:12

Tim S.


I believe you are looking for Math.Ceiling

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

That will give you 44

like image 23
Habib Avatar answered Dec 31 '22 09:12

Habib