Exact Change - comparison with zero (probably) not working

Exact Change - comparison with zero (probably) not working
0.0 0

#1

Hello, I’m currently stuck in this problem.

[UPDATE] It is working now, but FCC expects 0.50 to be a float value. I tried to set the decimal digits with toFixed(2) and parse it with parseFloat, but parseFloat deletes the zero ( 0.5 ). Can someone enlighten me? Thanks in advance!

  ["PENNY", 0.00], ["NICKEL", 0.00], ["DIME", 0.00], ["QUARTER", 0.00], ["ONE", 0.00], ["FIVE", 0.00], ["TEN", 0.00], ["TWENTY", 0.00], ["ONE HUNDRED", 0.00]
];

function get_unit(unit){
  return {
    0: 0.01, 1:0.05, 2:0.10, 3:0.25, 4: 1.00, 5:5.00,6: 10.00, 7: 20.00, 8: 100.00
  }[unit];
}

function checkCashRegister(price, cash, cid) {
  if(price>cash) return "Insufficient Funds";
  var total=0,value=cash-price;
  var temp_change = [];
  for(var i=0; i<cid.length; i++) {
    total += cid[i][1];
  }
  total = parseFloat(total.toFixed(2));
  value = parseFloat(value);
  if(total < value) return "Insufficient Funds";
  if(total == value) return "Closed";
  for(i=cid.length-1;i>=0;i--) {
    while(value >= parseFloat(get_unit(i))) {
      value = value - get_unit(i);
      change[i][1] += get_unit(i);
      cid[i][1] -= get_unit(i);
      if(value==0){break;}
    }
  }
  for(i=cid.length-1;i>=0;i--) {
    if(change[i][1] == 0) change.splice(i,1);
    else change[i][1] = change[i][1].toPrecision(2);
  }
  // Here is your change, ma'am.
  return change;
}

// Example cash-in-drawer array:
// [["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]]

checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1.00], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);

Link to the challenge:


#2

As you are aware, the 2nd element of each subarray should be a number and not a string. So, leave it as a float. 0.5 and 0.50 are the same value. As long as you return 0.5, it will pass the test.

You have another issue you appearantly have missed. Because you have declared change as a global variable, it is retaining it’s value from the previous test each time a new test executes. You need to move it inside the checkCashRegister function and then deal with the rounding error you are getting on a few of the tests.


#3

Thank you, kind sir!