0

I am not asking how i can write this program in another way. I made mistake in program so question is not duplicate. my question is what is error or missing thing in program. I just want to learn that and remove it.

My program make error for some situation that includes number that multiple of 0.1, 0.05 or 0.01 but for other numbers it run properly. For example it returns insufficient funds for this input (price(3.3) , cash(10.0)) instead of [five, 5] , [one ,1] ,[quarter,0.5], [dime,0.2]. I think algorithm is correct but there is something wrong that I cant see.

function checkCashRegister(price, cash, cid) {
  var left = cash - price;
  var toplam = 0;
  var paralar = [0.01, 0.05, 0.10, 0.25, 1.00, 5.00, 10.00, 20.00, 100.00];
  var artan = [];
  for (var i = 0; i < cid.length; i++) {
    toplam += cid[i][1];
  }

  if (left > toplam) {
    return "Insufficient Funds";
  } else if (left === toplam) {
    return "Closed";
  }

  var t = paralar.length - 1;
  for (var t = paralar.length - 1; t >= 0; t--) {
    if (left >= paralar[t]) {
      var sayac = 0;
      while (left >= paralar[t] && cid[t][1] > 0) {
        left -= paralar[t];
        sayac += paralar[t];
        cid[t][1] -= paralar[t];
      }
      var bos = [cid[t][0], sayac];
      artan.push(bos);
    }
  }

  if (left > 0) {
    return "Insufficient Funds";
  }

  return artan;
}
checkCashRegister(3.26, 100.00, [
  ["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]
]);

this example return insufficient funds. but if i change 3.26 to 3.25 it return correct string.

yuga
  • 3
  • 4
  • 1
    http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Xotic750 Sep 14 '16 at 21:48
  • Converting everything to PENNY (*100) and then back (/100) should fix your problem I believe. – Xotic750 Sep 14 '16 at 22:06

0 Answers0