Round off the decimal place of a number to the next multiple of 0.05

Viewed 1631

I want to Round off the decimal place of a number to the next multiple of 5 I have tried this but it's not working for decimal places

const roundOff = (num) =>{

 let temp = parseFloat(num.toFixed(2)) // to make it 2 place decimal
 return Math.ceil(temp / 5) * 5

  }

roundOff(54.5678)  // should give 54.60
roundOff(43.738)   // should give 43.75
roundOff(89.982)   // should give 90.00 
roundOff(80.034)   // should give 80.05
2 Answers

const roundOff = (num) =>{
 return (Math.ceil(num * 20) / 20).toFixed(2)
}

console.log(roundOff(54.5678))  // should give 54.60
console.log(roundOff(43.738))   // should give 43.75
console.log(roundOff(89.982))   // should give 90.00 
console.log(roundOff(80.034)) 

One option for doing this would be as follows:

  • Multiply the value by 20.
  • Use Math.round to round to the nearest integer.
  • Divide by 20 again.

For example:

double rounded = Math.round(x * 20.0) / 20.0;
Related