javascript:将浮点数四舍五入到最接近的 .25(或其他什么..)

javascript: rounding a float UP to nearest .25 (or whatever...)

本文关键字:其他 什么 最接近 浮点数 四舍五入 javascript      更新时间:2023-09-26

我能找到的所有答案都是四舍五入到最接近的,而不是接近的值......例如

1.0005 => 1.25  (not 1.00)
1.9   => 2.00
2.10 => 2.25
2.59 => 2.75   etc.

这似乎是很基本的,但这让我难倒了。但这必须四舍五入,而不是接近,这是一件相对容易的事情。

数字除以0.25(或您想要四舍五入到的最接近的任何分数)。

向上舍入到最接近的整数。

将结果乘以 0.25 .

Math.ceil(1.0005 / 0.25) * 0.25
// 1.25
Math.ceil(1.9 / 0.25) * 0.25
// 2
// etc.

function toNearest(num, frac) {
  return Math.ceil(num / frac) * frac;
}
var o = document.getElementById("output");
o.innerHTML += "1.0005 => " + toNearest(1.0005, 0.25) + "<br>";
o.innerHTML += "1.9 => " + toNearest(1.9, 0.25) + "<br>";
o.innerHTML += "2.10 => " + toNearest(2.10, 0.25) + "<br>";
o.innerHTML += "2.59 => " + toNearest(2.59, 0.25);
<div id="output"></div>

将数字乘以 4,对结果使用 Math.ceil,然后将该数字除以 4。

只需乘

以 4 并取 4 倍的 ceiled 值。

var values = [1.0005, 1.9, 2.10, 2.59],
    round = values.map(function (a) { return Math.ceil(a * 4) / 4; });
document.write('<pre>' + JSON.stringify(round, 0, 4) + '</pre>');

其他除法和乘法不适用于某些值,例如 1.59 您可以尝试自定义圆角函数

function customRound(x) {
    var rest = x - Math.floor(x)
    if (rest >= 0.875) {
        return Math.floor(x) + 1
    } else if (rest >= 0.625) {
        return Math.floor(x) + 0.75
    } else if (rest >= 0.375) {
        return Math.floor(x) + 0.50
    }  else if (rest >= 0.125){
        return Math.floor(x) + 0.25
    } else {
        return Math.floor(x)
    }
}
相关文章: