Cash Register Algorithm problem

Hey i’m doing Cash Register Algorithm and i have a problem, the subtraction of 0.47 - 0.01 results in 0.45999999999999996, i don’t realise if i’m doing something wrong or is a bug. Heres my code:

function checkCashRegister(price, cash, cid) {
  var changeNeeded = cash - price;
  var change = { status: "", change: [] }
  var values = {
    "PENNY": 0.01,
    "NICKEL": 0.05,
    "DIME":	0.1,
    "QUARTER": 0.25,
    "ONE": 1,
    "FIVE":	5,
    "TEN": 10,
    "TWENTY": 20,
    "ONE HUNDRED":	100
  }

  for(var i = (cid.length - 1); i > -1; i--){
    if(values[cid[i][0]] <= changeNeeded & cid[i][1] > 0 & changeNeeded > 0){
      change.change.push([cid[i][0], 0]) 
      while(cid[i][1] > 0 & changeNeeded > 0 & values[cid[i][0]] <= changeNeeded){
        changeNeeded -= values[cid[i][0]];
        cid[i][1] -= values[cid[i][0]];
        change.change[change.change.length - 1][1] += values[cid[i][0]];
        console.log(changeNeeded)
      }
    }
  }
  
  var totalCash = 0;
  for(var x = 0; x < cid.length - 1; x++){
    totalCash += cid[x][1];
  }

  if(changeNeeded > 0){
    change = {status: "INSUFFICIENT_FUNDS", change: []}
    return change;
  } else if(changeNeeded == 0 & totalCash == 0){
    change.status = "CLOSED";
    return change;
  } else {
    change.status = "OPEN";
    return change;
  }
}

checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])

Thanks :smiley:

Hi @Astrank :grinning:

No, nothing wrong with your code, most decimal fractions cannot be represented exactly in binary, use

number.toFixed(x)

Where x is the number of decimals you want and number is the result of the subtraction.

1 Like

this will solve your mistery:

1 Like

Number.toFixed(2) should do the trick.

1 Like

Oh didn’t know that! This should solve my problem. Thank you!!

Thanks! I’m gonna watch it right now :slight_smile: