目前js常用四舍五入方法存在bug,无法正确计算特殊数字。
例如:var a=8.745;
alert(a.toFixed(2));//8.74
alert(a.toFixed(2));//8.74
alert(a.toPrecision(3));//8.74
alert(Math.floor(a*100)/100);//8.74
alert(Math.round(a*100)/100);//8.74
原因是 alert(a*100);874.4999999999999
解决方案如下:
//计算两个数的乘法
function accMul(arg1,arg2){
var m=0,s1=arg1.toString(),s2=arg2.toString();
try{m+=s1.split(".")[1].length}catch(e){}
try{m+=s2.split(".")[1].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
//计算四舍五入,保留两位小数
function keepTwoDecimal(num) {
var result = parseFloat(num);
if (isNaN(result)) {
alert('传递参数错误,请检查!');
return false;
}
result = Math.round(accMul(num,100)) / 100;
return result;
}
alert(a);//8.745
alert(keepTwoDecimal(a));//8.75