原文連接: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()是四舍五入