Javascript舍入数字最接近0.5

Joh*_*dep 79 javascript


有人可以告诉我如何将数字四舍五入到最接近的0.5.
我必须根据屏幕分辨率在网页中缩放元素,因此我只能将字体大小以pts指定为1,1.5或2及以上等.

如果我将其四舍五入到小数点后1位或没有.我怎样才能完成这份工作?

new*_*ron 162

编写自己的函数,乘以2,舍入,然后除以2,例如

function roundHalf(num) {
    return Math.round(num*2)/2;
}
Run Code Online (Sandbox Code Playgroud)

  • @sfdxbomb 你检查过吗?在我的浏览器控制台中 `roundHalf(15.27)` 返回 15.5 (4认同)

Mic*_*eal 61

这是一个更通用的解决方案,可能对您有用:

function round(value, step) {
    step || (step = 1.0);
    var inv = 1.0 / step;
    return Math.round(value * inv) / inv;
}
Run Code Online (Sandbox Code Playgroud)

round(2.74, 0.1) = 2.7

round(2.74, 0.25) = 2.75

round(2.74, 0.5) = 2.5

round(2.74, 1.0) = 3.0

  • @Deilan 我猜是“逆”。 (3认同)
  • “inv”是什么意思?`inv` 变量代表什么? (2认同)

小智 14

只是上述所有答案的精简版本:

Math.round(valueToRound / 0.5) * 0.5;
Run Code Online (Sandbox Code Playgroud)

通用的:

Math.round(valueToRound / step) * step;
Run Code Online (Sandbox Code Playgroud)


小智 5

扩展 newtron 的最高答案,使其四舍五入超过 0.5

function roundByNum(num, rounder) {
    var multiplier = 1/(rounder||0.5);
    return Math.round(num*multiplier)/multiplier;
}

console.log(roundByNum(74.67)); //expected output 74.5
console.log(roundByNum(74.67, 0.25)); //expected output 74.75
console.log(roundByNum(74.67, 4)); //expected output 76

Run Code Online (Sandbox Code Playgroud)