例如,我需要将6.688689舍入到6.7,但它总是显示7。
我的方法:
Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or
Math.round(6.688689, 2);
但结果总是一样的7…我做错了什么?
例如,我需要将6.688689舍入到6.7,但它总是显示7。
我的方法:
Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or
Math.round(6.688689, 2);
但结果总是一样的7…我做错了什么?
当前回答
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
其他回答
Number((6.688689).toFixed(1)); // 6.7
如果你现在正在使用Browserify,你将不得不尝试:roundTo一个非常有用的NPM库
float(value,ndec);
function float(num,x){
this.num=num;
this.x=x;
var p=Math.pow(10,this.x);
return (Math.round((this.num).toFixed(this.x)*p))/p;
}
我有很好的解决方案,如果toFixed()不工作。
function roundOff(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
例子
roundOff(10.456,2) //output 10.46
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;
};