Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding in steps of 20 (or X) in JavaScript?

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!

like image 583
user1856596 Avatar asked Jan 31 '13 14:01

user1856596


4 Answers

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

like image 31
Moritz Roessler Avatar answered Nov 18 '22 00:11

Moritz Roessler


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
like image 177
Cerbrus Avatar answered Nov 17 '22 23:11

Cerbrus


Perhaps with something like that

number = Math.ceil( (number - 50) / 20 ) * 20 + 50;
like image 1
Spin0us Avatar answered Nov 18 '22 01:11

Spin0us


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.

like image 1
Bob Avatar answered Nov 18 '22 01:11

Bob