How to round number to the closest 50 in Javascript
11,956
Solution 1
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))
Solution 2
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.
Solution 3
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.
Author by
ggsplet
Updated on June 19, 2022Comments
-
ggsplet over 1 year
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.
-
Douwe de Haan over 6 yearsI thought that too, but after reading it a few more times it dawned on me he wants the closest 50-number.
-
jjr2000 over 6 years@DouwedeHaan Thanks, I've edited my answer to reflect this
-
Phil Tune over 2 years
Number.prototype.nearest = function(n) { return Math.round(this / n) * n}
const num = 534; console.log(num.nearest(50)) // 550