# Cash register Challenge - Hard Coded Division Error?

I was brainstorming how to solve this problem and debugging as I went and encountered the following issue - \$2.05/0.05 gives me the result of 40.999999 not 41. Anyone else encountered this issue? Am I missing something? All the other formulas seem to work fine. See the code below:

function checkCashRegister(price, cash, cid) {
//define primary variables
const p = 0.01;
const n = 0.05;
const d = 0.1;
const q = 0.25;
const db1 = 1;
const db5 = 5;
const db10 = 10;
const db20 = 20;
const db100 = 100;
let change = cash - price;
let currState = {status: “”, change: };

let pRoll = 0;
let nRoll = 0;
let dRoll = 0;
let qRoll = 0;
let db1Roll = 0;
let db5Roll = 0;
let db10Roll = 0;
let db20Roll = 0;
let db100Roll = 0;

// determine # of coins and bills in drawer

for (let i = 0 ; i < cid.length; i++) {
switch ( cid[i][0]) {
case “PENNY”:
pRoll = (cid[i][1])/p;
break;
case “NICKEL”:
nRoll = (cid[i][1])/n;
break;
case “DIME”:
dRoll = (cid[i][1])/d;
break;
case “QUARTER”:
qRoll = (cid[i][1])/q;
break;
case “ONE”:
db1Roll = (cid[i][1])/db1;
break;
case “FIVE”:
db5Roll = (cid[i][1])/db5;
break;
case “TEN”:
db10Roll = (cid[i][1])/db10;
break;
case “TWENTY”:
db20Roll = (cid[i][1])/db20;
break;
case “ONE HUNDRED”:
db100Roll = (cid[i][1])/db100;
break;
}
}
console.log(pRoll);
console.log(nRoll);
console.log(dRoll);
console.log(qRoll);
console.log(db1Roll);
console.log(db5Roll);
console.log(db10Roll)
console.log(db20Roll);
console.log(db100);
return currState;

}

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

Yes, many many people have encountered this issue because it is a common problem for all programming languages. It has to do with how floating point numbers (i.e. numbers with decimals in them) are represented in a computer. Because there are infinite amounts of floating point numbers it is impossible to represent them all and thus some amount of approximation needs to be done. Thus, you sometimes get weird answers for seemingly simple math problems, for example, in JS:

``````0.1 + 0.2 returns 0.30000000000000004
``````

So you’ll need to work around this.

Thank you for the explanation. Looks like things just got a bit more complicated.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.