Javascript:减法期间的浮点错误

时间:2018-02-25 06:06:27

标签: javascript

顾客去杂货店。他们买了一加仑牛奶。牛奶是3.26美元。客户支付100美元。他们预计会有96.74美元的变化。

收银员必须通过查看cid中的最新信息(现金抽屉)来回报更改。因此,他们可能会退还4张20美元的钞票,10美元的钞票,5美元的钞票,10美元的钞票,2美元的钞票和4美分。或者可能是不同的组合,取决于抽屉中可用的钞票。

以下代码运行正常,但我收到意外的浮点错误。



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]]




调试器显示浮点错误

在:

enter image description here

之后(1步之后)

enter image description here

0 个答案:

没有答案