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

我的方法:

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

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


当前回答

对这个答案的小调整:

function roundToStep(value, stepParam) {
   var step = stepParam || 1.0;
   var inv = 1.0 / step;
   return Math.round(value * inv) / inv;
}

roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55
roundToStep(2, 0.01) = 2

其他回答

Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

我认为下面的功能可以帮助

function roundOff(value,round) {
   return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}

用法:roundOff(600.23458,2);会返回600.23吗

> +(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
Math.round((6.688689 + Number.EPSILON) * 10) / 10

解决方案被盗自https://stackoverflow.com/a/11832950/2443681

这应该适用于几乎任何浮点值。它不强制十进制计数。目前尚不清楚这是否是一项要求。应该比使用toFixed()更快,根据对其他答案的注释,它也有其他问题。

一个很好的实用函数来四舍五入所需的十进制精度:

const roundToPrecision = (value, decimals) => {
  const pow = Math.pow(10, decimals);
  return Math.round((value + Number.EPSILON) * pow) / pow;
};