在js中进行以元为单位进行金额计算时,使用parseFloat会产生精度问题。
float精度问题有什么
varprice=10.99;
varquantity=7;
varneedPay=parseFloat(price*quantity);
needPay的正确结果应该是76.93元但是运行后发现needPay为76.93000000000001
此情况可通过toFixed(n)方法修正但是这个方法对js版本要求较高不能兼容ie5
float精度解决方案
将元为单位的金额乘以100换算为分进行计算
varprice=10.99
varquantity=7
varneedPay=Math.floor(parseFloat(price*100*quantity))/100;
parseFloat(price*100*quantity)的计算结果是7693.000000000001使用Math.round()方法四舍五入,再除100即为正确的结果
PS:顺便学到了一点:Math.ceil()Math.floor()Math.round()的区别
Math.ceil()是向上取整
Math.floor()是向下取整
Math.round()是四舍五入
复制代码
//保留两位小数
//功能:将浮点数四舍五入,取小数点后2位
functiontoDecimal(x){
varf=parseFloat(x);
if(isNaN(f)){
return;
}
f=Math.round(x*100)/100;
returnf;
}