js中进行金额计算 parseFloat 会产生精度问题


在js中进行以元为单位进行金额计算时 使用parseFloat会产生精度问题

var price = 10.99;var quantity = 7;
var needPay = parseFloat(price * quantity);

needPay的正确结果应该是76.93元  但是运行后发现needPay为76.93000000000001 
此情况可通过 toFixed(n)  方法修正 但是这个方法对 js版本要求较高 不能兼容ie5

另一个解决方案是: 将元为单位的金额乘以100换算为分进行计算

var price = 10.99
var quantity = 7
var needPay = Math.floor(parseFloat(price*100 * quantity))/100;

parseFloat(price*100 * quantity)的计算结果是7693.000000000001   使用Math.round()方法四舍五入,再除100  即为正确的结果

Math.ceil() 是向上取整
Math.floor()是向下取整
Math.round()是四舍五入

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM