# Debugging Cash Register Function

Hello,

I’m working through the final JavaScript challenge (Cash Register). I’ve written a function to count the change, and keep track of the change given in the format needed to pass the challenge.

The function seems to work in all cases, EXCEPT when it gets down to counting pennies. Sometimes when change gets down to .01, it never counts down the last penny, resulting in an infinite loop.

``````function checkCashRegister(price, cash, cid) {
let cidArr = cid;
let valuesArr = [.01, .05, .1, .25, 1, 5, 10, 20, 100];
let changeGiven = 0;
let changeGivenArr = [];

function countChange(change, x){
console.log(change)
changeGiven = 0;
while (change > 0){
if (valuesArr[x] > change){
return countChange(Math.round(change * 100) / 100, x -1)
} else if (valuesArr[x] <= change){
while (cidArr[x][1] > 0 && valuesArr[x] <= change){
change -= valuesArr[x]
cidArr[x][1] -= Math.round(valuesArr[x])
changeGiven += valuesArr[x]
}
changeGivenArr.push([cidArr[x][0], changeGiven])
return countChange(Math.round(change * 100) / 100, x - 1)
}
}

console.log(changeGivenArr)
return change;

}

console.log(countChange(.12, valuesArr.length -1))

}

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

Returns:

``````[ [ 'DIME', 0.1 ], [ 'PENNY', 0.02 ] ]
0 // The correct amount
``````

However, when passing in: values like .03, .04, .08, .09, .13, .18 etc… I get an infinite loop with .01 in the console.

Whats confusing to me is passing in values that require pennies like .01, .02, .12, .17 etc… returns the correct solution.

Can someone shed some light on what is going on here?

I suggest to watch this

Value like 0.1 cannot be represented precisely in a binary. To avoid a floating pointing division imprecision, I converted values into cents first

``````const valueArr = [1, 5, 10, 25, 100, 500, 1000, 2000, 10000];
let change = ... ; //in integer
``````

and used integer division. I convert the values back to decimals while building the change array.

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