Ryan
Ryan

Reputation: 151

Rounding up to the nearest multiple of 5

I am trying to write a Javascript function rounding up to the nearest multiple of 5. But you only round up if the difference between the variable and the roundup to the multiple of 5 is less than 3. (so 53 would round up to 55, but 52 would stay 52.)

Also if the grade is < 38 its an F.

The code below is what I have but it is not running properly. How can I fix it?

Thanks!!

grade = 71
function roundGrade (grade) {
const remainder = grade % 5
if (grade < 38) {
	return "fail";  }
else if (remainder >= 3) {
	grade; }
else if (remainder < 3) {
  grade-remainder+5
}
}

Upvotes: 0

Views: 946

Answers (2)

Taki
Taki

Reputation: 17654

calculate the remainder of grade / 5 and add it to the grade if the remaining is less than 3, otherwise return the grade as is.

const grade1 = 71
const grade2 = 73
const grade3 = 33

function roundGrade(grade) {
  if (grade < 38) return "fail"

  const rem = grade % 5;
  return rem < 3 ? grade : grade + (5 - rem)
}

console.log(roundGrade(grade1))
console.log(roundGrade(grade2))
console.log(roundGrade(grade3))

Upvotes: 2

Obsidian Age
Obsidian Age

Reputation: 42314

If the remainder is 3 or above, you simply need to add 5 and subtract the remainder, which can be done with grade += 5 - remainder. Also note that you don't need your second else if conditional at all, as you only want to modify grade if the remainder is greater than or equal to 3. Finally, you need to make sure that your function actually returns grade with return grade.

This can be seen in the following:

function roundGrade(grade) {
  const remainder = grade % 5;
  if (grade < 38) {
    return "fail";
  } else if (remainder >= 3) {
    grade += 5 - remainder;
  }
  return grade;
}

console.log(roundGrade(71));
console.log(roundGrade(74));

Upvotes: 3

Related Questions