Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round number to the closest 50 in Javascript

I need help with the following.

I would like to round calculated numbers this way:

Example: 132 goes to 150, 122 goes to 100

  • 0-24,99 goes to 0
  • 25-74,99 goes to 50
  • 75-124,99 goes to 100
  • and so on..

I need to do this in JS because user will insert some values, then the number will be calculated and this number needs to bi rounded.

like image 231
ggsplet Avatar asked May 10 '17 11:05

ggsplet


3 Answers

Try this .Math.round(num / 50)*50

function roundnum(num){
return Math.round(num / 50)*50;
}
console.log(roundnum(22))
console.log(roundnum(74))
console.log(roundnum(89))
console.log(roundnum(162))
console.log(roundnum(190))
console.log(roundnum(224))
console.log(roundnum(225))
like image 138
prasanth Avatar answered Oct 18 '22 00:10

prasanth


From what I've understood from your number ranges you are trying to round to intervals of 50.

To do this all that is needed is to divide your number by 50, round that and then times it by 50 again, like so

Math.round(num / 50) * 50

This function can be adapted to round to pretty much any number you would want just by changing the numbers used to times and divide.

like image 6
jjr2000 Avatar answered Oct 17 '22 23:10

jjr2000


You can use this function:

function closest50(number) {
  return Math.round(number / 50) * 50
}

console.log(closest50(0));
console.log(closest50(24));
console.log(closest50(24.99));
console.log(closest50(63));
console.log(closest50(132));

This divides the number by 50, rounds it down and than multiplies by 50 again.

like image 2
Douwe de Haan Avatar answered Oct 17 '22 22:10

Douwe de Haan