如何将小数舍入到最接近的 0.5(0.5、1.5、2.5、3.5)

How to round a decimal to the nearest 0.5 (0.5, 1.5, 2.5, 3.5)

我想将数字四舍五入到最接近的 0.5。并非 0.5 的每个因素, 只是 0.5

例如,0.5, 1.5, 2.5, -1.5, -2.5 1, 1.5, 2, 2.5.

我只是解释它让自己感到困惑,所以这里有一些预期输出的例子。

0.678 => 0.5
0.999 => 0.5
1.265 => 1.5
-2.74 => -2.5
-19.2 => -19.5

我尝试了以下代码但没有成功,

let x = 1.296;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // 1.5 (Correct!)
let x = -2.6;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // -3.5 (WRONG, should be -2.5)

代码在我看来很有意义,但不适用于负数。我缺少什么能让这项工作成功?

首先,您可以通过

四舍五入为整数
let x = 1.296;
let y = Math.round(x);

那么,可以先减0.5,再舍入,再加0.5

let x = 1.296;
let y = Math.round(x-0.5);
let z = y + 0.5;

你可以试试这个逻辑:

  • 从数字中获取小数部分。
  • 检查值是正数还是负数。基于此初始化一个因素
    • 积极保持1
    • 负数保持-1
  • 0.5乘以因数并加上小数

var data = [ 0.678, -0.678, 0.999, 1.265, -2.74, -19.2 ]

const output = data.map((num) => {
  const decimal = parseInt(num)
  const factor = num < 0 ? -1 : 1;
  return decimal + (0.5 * factor)
})

console.log(output)

function getValue (a){
   var lowerNumber = Math.floor(a);
   console.log(lowerNumber +0.5);
}

getValue(0.678);
getValue(0.999);
getValue(1.265);
getValue(-2.74);
getValue(-19.2);

看起来你想要较低的完整数字 + 0.5 ;