Don't get what's with the floats in my code

The problem

I don’t get why in my code what happens while trying to get the change due. Basically at some point, it switches to float with loooaaaddss of decimals ans mess up the result. Any clue what is happening there ?

I’m struggling to explain precisely what my issue is, so if not clear to you, please let me know so I try to better formulate it.

The code so far


function checkCashRegister(price, cash, cid) {

//Define change due
  let moneyDue = cash - price;

//Define an array with the currency
  let currency = [["PENNY", 0.01], ["NICKEL", 0.05], ["DIME", 0.1], ["QUARTER", 0.25], ["ONE", 1], ["FIVE", 5], ["TEN", 10], ["TWENTY", 20], ["ONE HUNDRED", 100]];

//Define change array 
  let changeDue = [["PENNY", 0], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]];

//Iterate through cid array (that is the same layout as currency and change arrays)
  for (var i = cid.length - 1; i > -1; i--) {
    //Check if money due is higher than currency
    while (moneyDue >= currency[i][1] 
      //Check if there's enough of the change
      && cid[i][1] >= currency[i][1]) {
      //Add one more currency item
      changeDue[i][1] += currency[i][1];
      //Decrease money due by same amount
      moneyDue -= currency[i][1];
      //Decrease cash in drawer by same amount
      cid[i][1] -= currency[i][1];
      };
  };

console.log(moneyDue);
console.log(changeDue);

}

checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: Cash Register

Link to the challenge:

This is one of the drawbacks of float numbers. Calculations with them can be imprecise.

try looking at this video, a possible solution is also mentioned

1 Like

why the devlopers did flag my work i was just tryina help

I am not sure exactly what you are trying to say, but I don’t think that any of that is accurate

Whenever someone runs into this I always ask them what the answer to 0.3 - 0.2 is and then have them ask JS what the answer is by typing it into the console :slight_smile:

1 Like