例如,我需要将6.688689舍入到6.7,但它总是显示7。

我的方法:

Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or 
Math.round(6.688689, 2);

但结果总是一样的7…我做错了什么?


当前回答

我的扩展圆函数:

function round(value, precision) {
  if (Number.isInteger(precision)) {
    var shift = Math.pow(10, precision);
    // Limited preventing decimal issue
    return (Math.round( value * shift + 0.00000000000001 ) / shift);
  } else {
    return Math.round(value);
  }
} 

示例输出:

round(123.688689)     // 123
round(123.688689, 0)  // 123
round(123.688689, 1)  // 123.7
round(123.688689, 2)  // 123.69
round(123.688689, -2) // 100
round(1.015, 2) // 1.02

其他回答

我有很好的解决方案,如果toFixed()不工作。

function roundOff(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

例子

roundOff(10.456,2) //output 10.46
> +(6.688687).toPrecision(2)
6.7

JavaScript中的Number对象有一个方法,它可以完全满足您的需要。该方法是Number.toPrecision([precision])。

就像. tofixed(1)一样,它将结果转换为字符串,并且需要将其转换回数字。这里使用+前缀完成。

在我的笔记本电脑上进行简单的基准测试:

number = 25.645234 typeof number
50000000 x number.toFixed(1) = 25.6 typeof string / 17527ms
50000000 x +(number.toFixed(1)) = 25.6 typeof number / 23764ms
50000000 x number.toPrecision(3) = 25.6 typeof string / 10100ms
50000000 x +(number.toPrecision(3)) = 25.6 typeof number / 18492ms
50000000 x Math.round(number*10)/10 = 25.6 typeof number / 58ms
string = 25.645234 typeof string
50000000 x Math.round(string*10)/10 = 25.6 typeof number / 7109ms
Number((6.688689).toFixed(1)); // 6.7

如果你在node.js环境下,你可以尝试mathjs

const math = require('mathjs')
math.round(3.1415926, 2) 
// result: 3.14

我认为这个函数会有帮助。

 function round(value, ndec){
    var n = 10;
    for(var i = 1; i < ndec; i++){
        n *=10;
    }

    if(!ndec || ndec <= 0)
        return Math.round(value);
    else
        return Math.round(value * n) / n;
}


round(2.245, 2) //2.25
round(2.245, 0) //2