我知道 Math.round 会将数字舍入到最接近的整数。
我需要的是在特定范围内对数字进行四舍五入。例如
如果 num=4.50 且 range=0.1
所以 4.5 的 +- 0.1 中的数字应四舍五入为 4.5
即mathrangeRound(4.44) =4.5 和 MathrangeRound(4.6) =4.5
感谢任何帮助。
谢谢。
最佳答案
你可以尝试这样的事情:
function aggr(num, pre, base){
return Math.abs(base - num) <= pre ? base : num
}
console.log(aggr(4.44, 0.1, 4.5))
console.log(aggr(4.6, 0.1,4.5))
console.log(aggr(4.8, 0.1,4.5))
console.log(aggr(4.8, 0.3,4.5))
关于javascript - 在 Javascript 中的范围内舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40152698/