【问题标题】:How to round a decimal to the nearest 0.5 (0.5, 1.5, 2.5, 3.5)如何将小数四舍五入到最接近的 0.5(0.5、1.5、2.5、3.5)
【发布时间】:2021-04-17 01:19:26
【问题描述】:

我想将一个数字四舍五入到最接近的0.5。不是0.5 的所有因素,只是 0.5s。

例如,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)

代码在我的脑海中是有意义的,但不适用于负数。我缺少什么可以使这项工作正常进行?

【问题讨论】:

    标签: javascript node.js rounding


    【解决方案1】:

    首先,你可以通过四舍五入到整数

    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;
    

    【讨论】:

      【解决方案2】:

      你可以试试这个逻辑:

      • 从数字中获取小数部分。
      • 检查值是正数还是负数。基于此初始化一个因子
        • 对于积极的保留它 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)

      【讨论】:

        【解决方案3】:

        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 ;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-04-01
          • 2014-06-20
          • 2012-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多