5

假设我有一个在已知最小值和最大值之间有 10 个值的刻度。如何在最小值和最大值之间获得最接近的值。例子:

min = 0, max = 10, value = 2.75 -> expected: value = 3
min = 5, max = 6, value = 5.12 -> expected: value = 5.1
min = 0, max = 1, value = 0.06 -> expected: value = 0.1
4

6 回答 6

5

你可以使用这样的东西

function nearest(value, min, max, steps) {
  var zerone = Math.round((value - min) * steps / (max - min)) / steps; // bring to 0-1 range    
  zerone = Math.min(Math.max(zerone, 0), 1) // keep in range in case value is off limits
  return zerone * (max - min) + min;
}

console.log(nearest(2.75, 0, 10, 10)); // 3
console.log(nearest(5.12, 5, 6, 10)); // 5.1
console.log(nearest(0.06, 0, 1, 10)); // 0.1

演示在http://jsfiddle.net/gaby/4RN37/1/

于 2012-11-29T21:54:10.907 回答
2

你的场景对我来说没有多大意义。为什么 .06 舍入到 1 而不是 .1 而是 5.12 舍入到 5.1 具有相同的比例(1 个整数)?这很令人困惑。

无论哪种方式,如果您想四舍五入到精确的小数位数,请查看: http ://www.javascriptkit.com/javatutors/round.shtml

var original=28.453

1) //round "original" to two decimals
var result=Math.round(original*100)/100  //returns 28.45

2) // round "original" to 1 decimal
var result=Math.round(original*10)/10  //returns 28.5

3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000  //returns 8.111

通过本教程,您应该能够完全按照您的意愿行事。

于 2012-11-29T21:15:22.580 回答
1

也许更容易理解:

var numberOfSteps = 10;
var step = (max - min) / numberOfSteps;
var difference = start - min;
var stepsToDifference = Math.round(difference / step);
var answer = min + step * stepsToDifference;

这也允许您更改序列中的步数。

于 2012-11-29T21:20:20.203 回答
1

我建议这样的事情:

var step = (max - min) / 10;
return Math.round(value / step) * step;
于 2012-11-29T21:21:22.233 回答
1

例如,我遇到了问题,5.7999997而不是断奶5.8。这是我的第一个修复(对于 java ......)。

public static float nearest(float val, float min, float max, int steps) {
    float step = (max - min) / steps;
    float diff = val - min;
    float steps_to_diff = round(diff / step);
    float answer = min + step * steps_to_diff;
    answer = ((int) (answer * steps)) / (float) steps;
    return answer;
}

但是,使用它nearest(6.5098, 0, 10, 1000)我会得到6.509而不是想要的6.51. 这为我解决了这个问题(当值非常大时请注意溢出):

public static float nearest(float val, float min, float max, int steps) {
    val *= steps;
    min *= steps;
    max *= steps;
    float step = (max - min) / steps;
    float diff = val - min;
    float steps_to_diff = round(diff / step);
    float answer = min + step * steps_to_diff;
    return answer / (float) steps;
}
于 2019-01-12T19:19:40.503 回答
-1
var step = 10;
return Math.ceil(x / step) * step;
于 2019-04-17T09:22:36.037 回答