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

我的方法:

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

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


当前回答

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

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

其他回答

见下文

原始变量 = 28.59;

var result=Math.round(原*10)/10将返回28.6

希望这就是你想要的。

对这个答案的小调整:

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

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

const math = require('mathjs')
math.round(3.1415926, 2) 
// result: 3.14
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
+((6.688689 * (1 + Number.EPSILON)).toFixed(1)); // 6.7
+((456.1235 * (1 + Number.EPSILON)).toFixed(3)); // 456.124