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.
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);
I believe you are looking for Math.Ceiling
decimal number = 43.4M;
int roundedNumber = (int) Math.Ceiling(number);
That will give you 44
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