sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

原文连接:https://www.cnblogs.com/zhangruiqi/p/8486858.html

在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()是四舍五入

 

posted on 2020-12-23 21:13  sunny123456  阅读(1134)  评论(0编辑  收藏  举报