I have numbers starting at 50 and ending with 190. The steps are alwyas 20 -->
50, 70, 90, .... 190
Now I get a number from a text filed which has to be rounded according to this. So if I get 55, it should become 70, if I get 77, it should be 90. If I get 90, it should of course stay 90. I know how to do it steps of 10:
// 55 --> 60
number = Math.ceil(number / 10) * 10
How to round the number I get using steps of 20?
Thanks!
function round(number,x,o) {
o = ~~(o);
return o + Math.ceil((number - o)/ x ) * x
}
console.log(round (55,20,10)) //70
console.log(round (77,20,10)) //90
console.log(round (90,20,10)) //90
@Cerbrus thx to point that out
If you want to round in increments of x, with an offset:
function round(number, increment, offset) {
return Math.ceil((number - offset) / increment ) * increment + offset;
}
round(51, 20, 10) // 70
round(70, 20, 10) // 70
round(99, 20, 10) // 110
round(100, 20, 10) // 110
Perhaps with something like that
number = Math.ceil( (number - 50) / 20 ) * 20 + 50;
var number;
var a =number-10-((number-10)%20);
var result=a+30;
// does not work if num is 70 or 90 so
if(result-20==number)
Result=number;
Or as a one-liner:
var result=number+20-((number-10)%20) - result-20==number : 0 ? 20;
The logic is that first, you add 20 to the number. Take the number 77. 77+20=97. But, 77+20-7=90, what you want. And 7 is the difference between 77 and 70, the previous valid number. You can get the differencewith (number-10)%20. However, it doesn't work if number is OK to start out with, hence the logic at the end.
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