I need help with the following.
I would like to round calculated numbers this way:
Example: 132 goes to 150, 122 goes to 100
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.
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))
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.
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.
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