1

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;
}


1 Answers1

1

You need to round the parts to get an integer value, because of the problems with floating point arithmetic (Is floating point math broken?).

let price = 0.90;
let paid = 5;
let change = Math.round(paid * 100) - Math.round(price * 100);
let counter = 0;

console.log(100 * (paid - price), 'vs', change);

if (change >= 100) {
    counter = Math.floor(change / 100);
    console.log(counter + ' x 1 dollar');
    change %= 100;
}
if (change >= 50) {
    counter = Math.floor(change / 50);
    console.log(counter + ' x 50 cents')
    change %= 50;
}
if (change >= 20) {
    counter = Math.floor(change / 20);
    console.log(counter + ' x 20 cents')
    change %= 20;
} 
if (change >= 10) {
    counter = Math.floor(change / 10);
    console.log(counter + ' x 10 cents');
    change %= 10;
}
if (change >= 5) {
    counter = Math.floor(change / 5);
    console.log(counter + ' x 5 cents');
    change %= 5;
}
if (change >= 2) {
    counter = Math.floor(change / 2);
    console.log(counter + ' x 2 cents');
    change %= 2;
}
if (change >= 1) {
    console.log(Math.floor(counter) + ' x 1 cent');
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392