how to detect if JavaScript whole number is closer to another whole number? - Stack Overflow

In JavaScript, I may have a random number generated, that may be 3,123, or 3,001, or 2790, etc.. Which

In JavaScript, I may have a random number generated, that may be 3,123, or 3,001, or 2790, etc.. Which JavaScript method will help me out in returning a target whole integer because these values...

3,123, or 3,001, or 2790 are closer to 3000, rather than 4000 or 2000, or 1000.

Thanks for any advice.

In JavaScript, I may have a random number generated, that may be 3,123, or 3,001, or 2790, etc.. Which JavaScript method will help me out in returning a target whole integer because these values...

3,123, or 3,001, or 2790 are closer to 3000, rather than 4000 or 2000, or 1000.

Thanks for any advice.

Share Improve this question edited Sep 25, 2012 at 20:47 klewis asked Sep 25, 2012 at 20:00 klewisklewis 8,43816 gold badges69 silver badges112 bronze badges 2
  • 1 Your question is not clear, do you want to get the closest thousand of a number, the closest to a given target, the different distances towards a target, or something else? – Mahn Commented Sep 25, 2012 at 20:17
  • I fixed up my question for you Mahn – klewis Commented Sep 25, 2012 at 20:47
Add a ment  | 

2 Answers 2

Reset to default 5

You could sort them:

var numbers = [3123, 3001, 2790, 4000, 2000, 1000];
var target = 3000;
var closest = numbers.sort(function(a, b) {
  var a = Math.abs(a - target);
  var b = Math.abs(b - target);

  return a < b ? -1 : (a > b ? 1 : 0);
});

closest contains the numbers sorted by their distance from 3000.

Or you could use a long one-liner:

var sorted = numbers.map(function(value, index) {
  return [Math.abs(value - 3000), index];
}).sort().map(function(value, index) {
  return numbers[value[1]];
});

Try:

var rand_num = Math.floor(Math.random() * 10000);
Math.round((rand_num) / 1000) * 1000;

If rand_num is 3123, 3001 or 2790, it will be reduced to either 3.123, 3.001 and 2.729 respectively, rounded to 3.0 and multiplied to bee 3000.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745408385a4626417.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信