# Help With Cash Register Challenge

Hello,

I’ve been working on this challenge for a while, and I took a break. I recently just came back and I’ve been working on it, but I have just been stuck. I was wondering if any of you guys can provide any help on getting me on the right track to providing my own solution?

So, in the code, I’ve been using a loop to continuously subtract to get the proper change, but it keeps giving me weird values. I’ve been trying to figure that out for the longest.

Here is My Code:

``````function checkCashRegister(price, cash, cid) {
let changeCal = cash - price;
let drawerSum = 0;    // calculates sum of money in drawer.
let obj = {};
obj.status = " ";
obj.change = [];
let sum = 0;

/* Step 1: Iterate through 2d array */
for(let i=0; i < cid.length; i++) {
for(let j=0; j < cid[i].length; j++) {
if(isNaN(cid[i][j]) === false) {
drawerSum += cid[i][j]; // add up all the numbers
}
if(cid[i][j] === "PENNY") {
cid[i][j] = 0.01;
}
if(cid[i][j] === "NICKEL") {
cid[i][j] = 0.05;
}
if(cid[i][j] === "DIME") {
cid[i][j] = 0.1;
}
if(cid[i][j] === "QUARTER") {
cid[i][j] = 0.25;
}
if(cid[i][j] === "ONE") {
cid[i][j] = 1;
}
if(cid[i][j] === "FIVE") {
cid[i][j] = 5;
}
if(cid[i][j] === "TEN") {
cid[i][j] = 10;
}
if(cid[i][j] === "TWENTY") {
cid[i][j] = 20;
}
if(cid[i][j] === "ONE HUNDRED") {
cid[i][j] = 100;
}
}
}

/* Create a new 2D array by ordering it */
let cid2 = cid.sort(function(a, b) {
return b[0] - a[0];
})

loop1:
for(let i=0; i < cid2.length; i++) {
//loop2:
// for(let j=0; j < cid2[i].length; j++) {
if(changeCal < cid2[i][0]) {
continue; // Skip the iteration
}  else {
while(changeCal > 0) {
changeCal -= cid2[i][0];
sum += cid2[i][0];
console.log(sum);
if(sum >= cid2[i][1]) {
changeCal -= cid2[i+1][0];
//continue loop1;
break;
}
}
//console.log(sum);
console.log(changeCal);
}
// }
}

if(drawerSum < changeCal) {
obj.status = "INSUFFICIENT_FUNDS";
obj.change = [];
}
if(drawerSum === changeCal) {
obj.status = "CLOSED";
obj.change = cid;
}

return obj;
}
``````

All help is appreciated. Thanks!

You are encountering the so-called floating point error. Due to internal representation of the floating numbers, operations performed on such numbers can be imprecise. One of the typical example of it is following:

``````0.1 + 0.1 + 0.1 === 0.3
``````

The result of this might be surprising exactly because of the floating point error.

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