在javascript中添加两个浮点数产生奇怪的异常

时间:2018-04-27 11:46:31

标签: javascript math floating-point

问题发生在checkCashRegister函数的forEach循环中。

let values = {
  "PENNY": 0,
  "NICKEL": 0,
  "DIME": 0,
  "QUARTER": 0,
  "ONE": 0,
  "FIVE": 0,
  "TEN": 0,
  "TWENTY": 0,
  "ONE HUNDRED": 0,
  "TOTAL": 0,
}

function checkCashRegister(price, cash, cid) {
  cid.forEach((arr) => {
    values[arr[0]] = arr[1];
    console.log(`${values["TOTAL"]} + ${arr[1]} = ${values["TOTAL"] + arr[1]}`);
    values["TOTAL"] += arr[1]; 
  });

  let change = cash - price;

  console.log(values);
  return change;
}

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);

这应该只是将数组转换为一个对象并计算values.total中所有对象字段的总和,但由于某种原因,输出是这样的:

0 + 1.01 = 1.01
1.01 + 2.05 = 3.0599999999999996
3.0599999999999996 + 3.1 = 6.16
6.16 + 4.25 = 10.41
10.41 + 90 = 100.41
100.41 + 55 = 155.41
155.41 + 20 = 175.41
175.41 + 60 = 235.41
235.41 + 100 = 335.40999999999997
{ PENNY: 1.01,
  NICKEL: 2.05,
  DIME: 3.1,
  QUARTER: 4.25,
  ONE: 90,
  FIVE: 55,
  TEN: 20,
  TWENTY: 60,
  'ONE HUNDRED': 100,
  TOTAL: 335.40999999999997 }

为什么1.01 + 2.05 = 3.0599999999999996而不是3.06?简单地将数字四舍五入到最接近的第二个小数点并不困难,但我更愿意知道为什么会出现这个问题。

感谢。

0 个答案:

没有答案