【问题标题】:How to round figure if it is less then point 5 only in javascript [duplicate]如果仅在javascript中小于第5点,如何舍入数字[重复]
【发布时间】:2015-08-23 02:30:30
【问题描述】:

如果它小于任何 0.5 数字,我会尝试在 JavaScript 中对我的数字进行四舍五入。例如,如果我的值是 3.4,那么它应该是 3,但如果是 3.5,那么就不需要四舍五入了。如果小于 0.5,我只想对数字进行四舍五入。这是我用来四舍五入的代码。但它在两种情况下都将数字四舍五入

这段代码给了我结果 3.5

function rounded(){
               var val = 3.5; 
                var rounded = Math.round(val);
                console.log("rounded",rounded);
}

这段代码给了我结果 4 但我想要 3.5..

function rounded(){
                   var val = 3.6; 
                    var rounded = Math.round(val);
                    console.log("rounded",rounded);
    }

任何机构可以帮助我解决这个问题?

【问题讨论】:

  • 使用(val%1)<.5 ? round(val) : val
  • 对于 3.3 它给了我 3.5 但我想要 3.0 小于 3.5 我想要 3.0 而大于 3.6 我想要 3.5
  • 顺便说一句,您发布的第一个代码示例结果为 3。 Math.round 将四舍五入到最接近的整数。

标签: javascript


【解决方案1】:

使用Math.floor 向下舍入。

var round = function (num) {
   return Math.floor(num * 2) / 2;
};

console.log(round(3));  // 3
console.log(round(3.4));  // 3
console.log(round(3.5));  // 3.5
console.log(round(3.6));  // 3.5
console.log(round(4));  // 4

【讨论】:

  • 非常感谢它解决了我的问题:)
【解决方案2】:

这应该截断到最接近的 .5:

parseInt(x * 2) / 2;

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 2022-09-27
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    相关资源
    最近更新 更多