I'm trying to make a function that takes an amount of cash, and deducts the amount of coins/bills needed to make up that amount of cash from existing variables. The code I have looks like this:
var changeDue = 34.66;
// get number of each coin
var penny = 50;
var nickel = 50;
var dime = 50;
var quarter = 50;
var one = 50;
var five = 50;
var ten = 50;
var twenty = 50;
var hundred = 50;
function getChange(due) {
var currentDue = due;
while(currentDue > 0) {
if(currentDue >= 100 && hundred > 0){
hundred--;
currentDue -= 100;
}
else if(currentDue >= 20 && twenty > 0) {
twenty--;
currentDue -= 20;
}
else if(currentDue >= 10 && ten > 0) {
ten--;
currentDue -= 10;
}
else if(currentDue >= 5 && five > 0) {
five--;
currentDue -= 5;
}
else if(currentDue >= 1 && one > 0) {
one--;
currentDue -= 1;
}
else if(currentDue >= 0.25 && quarter > 0) {
quarter--;
currentDue -= 0.25;
}
else if(currentDue >= 0.1 && dime > 0) {
dime--;
currentDue -= 0.1;
}
else if(currentDue >= 0.05 && nickel > 0) {
nickel--;
currentDue -= 0.05;
}
else if(currentDue >= 0.01 && penny > 0) {
penny--;
currentDue -= 0.01;
}
}
console.log(currentDue);
}
getChange(changeDue);
What I'm trying to do with the while loop is to check if the amount of change due is above a certain bill/coin like one hundred and there are still coins or bills of this value available, and then deduct from the change due and amount of coins/bills. But this is resulting in an infinite loop, so I can't debug it.
I thought that since I am always deducting from currentDue and I have set such a high number of coins and bills I wouldn't have such a problem but I do. Can someone point out what I am doing wrong?
Thank you