我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
一个助手函数,其中rounding是默认舍入:
let rounding = 4;
let round = (number) => { let multiply = Math.pow(10,rounding); return Math.round(number*multiply)/multiply};
console.log(round(0.040579431));
=> 0.0406
其他回答
这可能会帮助您:
var result = Math.round(input*100)/100;
有关更多信息,您可以查看Math.round(num)vs num.toFixed(0)和浏览器不一致性
这是我想出的一个函数,用来进行“舍入”。我使用了double Math.round来补偿JavaScript的不准确乘法,因此1.005将正确舍入为1.01。
function myRound(number, decimalplaces){
if(decimalplaces > 0){
var multiply1 = Math.pow(10,(decimalplaces + 4));
var divide1 = Math.pow(10, decimalplaces);
return Math.round(Math.round(number * multiply1)/10000 )/divide1;
}
if(decimalplaces < 0){
var divide2 = Math.pow(10, Math.abs(decimalplaces));
var multiply2 = Math.pow(10, Math.abs(decimalplaces));
return Math.round(Math.round(number / divide2) * multiply2);
}
return Math.round(number);
}
从现有的答案中,我找到了另一个似乎很有效的解决方案,它也可以发送字符串,并消除尾随零。
function roundToDecimal(string, decimals) {
return parseFloat(parseFloat(string).toFixed(decimals));
}
如果你派一些公牛来,那就不算什么了。。就像“阿帕”一样。或者它可能会抛出一个错误,我认为这是正确的方法。无论如何,隐藏应该修复的错误(通过调用函数)是不好的。
对我来说,Math.rround()没有给出正确的答案。我发现Fixed(2)效果更好。以下是两者的示例:
console.log(数学舍入(43000/80000)*100);//错误的答案console.log(((43000/80000)*100).toFixed(2));//正确回答
使用Math.rround():
Math.round(num * 100) / 100
或者更具体地说,为了确保1.005这样的数字正确,请使用Number.EPSILON:
Math.round((num + Number.EPSILON) * 100) / 100