收银机FCC如何确定小数计算?

时间:2019-09-01 14:28:53

标签: javascript arrays

我不理解这些计算的逻辑。运行代码,然后告诉我0.000000000000数字从何而来。我添加了控制台输出,供您了解我的意思。

我尝试使用toFixed(2)修复此问题,但对于循环中的arr [i] [1]无效。

function checkCashRegister(price, cash, cid) {
  let result = {
    status: '',
    change: []
  }
  let arr1 = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100];
  let arr = [["PENNY", 0], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0],
  ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]];
  let change = cash - price;

  for (let i = arr1.length - 1; i >= 0; i--) {
    while (change > 0 && cid[i][1] > 0) {
      if (change < arr1[i]) {
        break;
      } else {
        arr[i][1] = arr[i][1] + arr1[i]
        cid[i][1] = cid[i][1].toFixed(2) - arr1[i]
        change = change.toFixed(2) - arr1[i];
        console.log('cid = ' + cid[i], ' - ' + arr1[i], 'arr = ' + arr[i], 'change = ' + change)
      }
    }
  }
  console.log((cid.map(e=>e[1]).reduce((a,b)=>a+b)))
  if(change != 0){
    result.status = 'INSUFFICIENT_FUNDS';
    return result;
  }else if((cid.map(e=>e[1]).reduce((a,b)=>a+b))==0){
    result.status = "CLOSED"
    result.change = arr;
    return result
}else{
  result.status = "OPEN"
  result.change = arr.filter(el => el[1] != 0).reverse();
  return result;
}
  console.log('arr = ' + arr)
  console.log('cid = ' + cid)
}


checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])

只需一些控制台输出,您便可以了解问题所在:

cid = PENNY,0.47  - 0.01 arr = PENNY,0.03 change = 0.47

cid = PENNY,0.45999999999999996  - 0.01 arr = PENNY,0.04 change = 0.45999999999999996

cid = PENNY,0.45  - 0.01 arr = PENNY,0.05 change = 0.45

cid = PENNY,0.44  - 0.01 arr = PENNY,0.060000000000000005 change = 0.44

0 个答案:

没有答案