我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
我回顾了这篇文章的每一个答案。以下是我对此事的看法:
常量nbRounds=7;常量舍入=(x,n=2)=>{常量精度=数学.pw(10,n)return数学舍入((x+Number.EPSILON)*precision)/精度;}设i=0;而(nbRounds>i++){console.log(“round(1.00083899,”,i,“)>”,round(1.00 08389,i))console.log(“圆形(1.83999305,”,i,“)>”,圆形(1.83999305,i))}
其他回答
使用Math.rround():
Math.round(num * 100) / 100
或者更具体地说,为了确保1.005这样的数字正确,请使用Number.EPSILON:
Math.round((num + Number.EPSILON) * 100) / 100
var roundUpto = function(number, upto){
return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);
toFixed(2):这里2是我们要舍入的位数。
我在MDN上找到了这个。他们的方法避免了前面提到的1.005的问题。
函数roundToTwo(num){return+(数学舍入(num+“e+2”)+“e-2”);}console.log(“1.005=>”,roundToTwo(1.005));console.log('10=>',roundToTwo(10));console.log('1.7777777=>',roundToTwo(1.7777777));console.log('9.1=>',roundToTwo(9.1));console.log('1234.5678=>',roundToTwo(1234.5678));
这里找到的答案都不正确。臭柴塞曼要求四舍五入,但你们都四舍五进。
要进行汇总,请使用以下命令:
Math.ceil(num * 100)/100;
number=(parseInt((number +0.005)*100))/100;
如果要正常舍入(2位小数),请添加0.005
8.123 +0.005=> 8.128*100=>812/100=>8.12
8.126 +0.005=> 8.131*100=>813/100=>8.13