问题描述:

I'm not 100% sure how to ask this question so please dont mark me down for that.. I will do my best.

how do I work out what range my number falls in?

eg:

var range = 100;

var myNum = 320;

Therfore my result would be 300 as that is the range 320 falls into.

further exampes would be:

var range = 100;

var myNum = 190;

result: 100

var range = 100;

var myNum = 864;

result: 800

and lastly:

var range = 50;

var myNum = 864;

result: 850

Hope this make sence.

网友答案:

This is the logic you're looking for:

var result = range * Math.floor(myNum / range);

Replace Math.floor by Math.ceil if you want to find the upper bound of the "range". The code above is an implementation of:

  • How often does range suit in range?
  • Multiply the previous result by range
  • The final result equals the "number range".
网友答案:

You can also subtract from myNum the modulus of myNum by range:

var result = myNum - (myNum % range);
网友答案:

result = myNum - (myNum % range)

myNum % range means "if I put range in my myNum as many times as I can, what integer will I have left?"

and you can subtract that from myNum and you get your result.

相关阅读:
Top