I need to use conditional statements only. I am trying to calculate the least amount of coins needed to return change. I thought I was getting there and my code works for most scenarios, but I realized I am getting some errors like this:
Input: Price: 0.90 Paid: 5 Output: 4 x 1 dollar 1 x 5 cents 2 x 2 cents
I found a similar question - Coin Change Algorithm JS , but the answers do not help me get over this issue in my code. Would appreciate any advise on what I am doing wrongly.
let price = 0.90;
let paid = 5;
let change = paid - price;
let counter = 0;
change = change*100;
if(change >= 100){
change = change/100;
counter = change;
console.log(counter.toFixed(0) + ' x 1 dollar');
change = (change * 100) % 100;
}
if(change >= 50) {
change = change/50;
counter = change;
console.log(counter.toFixed(0) + ' x 50 cents')
change = (change * 50) % 50;
}
if(change >= 20){
change = change/20;
counter = change;
console.log(counter.toFixed(0) + ' x 20 cents')
change = (change*20) % 20;
}
if(change >= 10){
change = change/10;
counter = change;
console.log(counter.toFixed(0) + ' x 10 cents');
change = (change * 10) % 10;
}
if(change >= 5){
change = change/5;
counter = change;
if(counter != 0){
console.log(Math.floor(counter) + ' x 5 cents');
change = (change * 5) % 5;
}
}
if(change >= 2){
change = change/2;
counter = change;
if(counter != 0){
console.log(Math.floor(counter) + ' x 2 cents');
}
change = (change * 2) % 2;
}
if(change >= 1){
change = change;
counter = change;
if(counter != 0){
console.log(Math.floor(counter) + ' x 1 cent');
}
change = (change * 1) % 1;
}