0

The problem occurs in the forEach loop in the checkCashRegister function.

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]]);

This should simply convert the array to an object and calculate the total of all the object fields in values.total but for some reason the output is this:

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 }

Why does 1.01 + 2.05 = 3.0599999999999996 instead of 3.06? It wouldn't be hard to simply round the number to the nearest second decimal point but i'd prefer to know why this problem is occurring at all.

Thanks.

Henry S
  • 35
  • 1
  • 6

0 Answers0