假设我有一个在已知最小值和最大值之间有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
答案 0 :(得分:3)
你可以使用这样的东西
function nearest(value, min, max, steps){
var zerone = Math.round((value-min)*steps/(max-min))/steps; // bring to 0-1 range
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
演示
答案 1 :(得分:1)
你的情景对我来说没什么意义。为什么.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
通过本教程,您应该能够完全按照自己的意愿行事。
答案 2 :(得分:1)
也许更容易理解:
var numberOfSteps = 10;
var step = (max - min) / numberOfSteps;
var difference = start - min;
var stepsToDifference = Math.round(difference / step);
var answer = min + step * stepsToDifference;
这也允许您更改序列中的步骤数。
答案 3 :(得分:1)
我建议这样的事情:
var step = (max - min) / 10;
return Math.round(value / step) * step;
答案 4 :(得分:0)
例如,我遇到的问题是我得到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;
}
答案 5 :(得分:-1)
var step = 10;
return Math.ceil(x / step) * step;