0

A customer goes to the grocery store. They buy a gallon of milk. The milk is $3.26. Customer pays $100. They expect change of $96.74.

Cashier has to give back change, by checking whats in the cid (cash in drawer). So they might give back four $20 bills, a $10 bill, a $5 bill, a $1bill, 2 dimes, and 4 pennies. Or maybe a different combination, depending on what bills are available in drawer.

The code below works fine except I get an unexpected floating point error.

function giveChange(change, cid) {
    const currencyReference = {
        "ONE HUNDRED": 100.00,
        "TWENTY": 20.00,
        "TEN": 10.00,
        "FIVE": 5.00,
        "ONE": 1.00,
        "QUARTER" : 0.25,
        "DIME" : 0.10,
        "NICKEL": 0.05,
        "PENNY" : 0.01,
    };

    let changeLeftOver = change;
    let changeReturned = [];
    
    // Iterate backwards in cid
    cid.slice().reverse().forEach(function(el) {
        debugger;
        let billType = el[0];
        let billTypeTotalValue = el[1];
        let billValue = currencyReference[billType];
        let billQuantity = billTypeTotalValue / billValue;
        let billReceived = 0;

        while (changeLeftOver >= billValue && billQuantity > 0) {
            changeLeftOver = changeLeftOver - billValue;
            billQuantity--;
            billReceived++;
        }

        if(billReceived > 0){
            changeReturned.push([billType, billReceived * billValue]);
        }
    });
    console.log(changeLeftOver);  // expected 0, got 0.0099999

    if (changeLeftOver !== 0){ return "Insufficient Funds";}
    return changeReturned;
}
giveChange(96.74, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
// should return [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15.00], ["ONE", 1.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]]

Debugger showing floating point error

Before:

enter image description here

After (1step later)

enter image description here

Vincent Tang
  • 3,758
  • 6
  • 45
  • 63

0 Answers0