2

I have a run into the much reviled floating point arithmetic problem. I'm working on a program that uses currency. And a little ways into developing my program, I realised that floating point arithmetic was causing problems for me. So I decided to convert the floating point numbers used to represent the values into integers that would hopefully avoid logic and comparison problems down the line...

But even this process of converting the floats to ints is not going smoothly. There is one value in particular that is causing an issue. I'm wondering why this particular value. Has anyone any suggestions that would be a better way to approach this problem. I can't use any libraries, it's part of an assessment project.

Here's the code:

function checkCashRegister(price, cash, cid) {

  price *= 100;

  cash *= 100;

  for (let i = 0; i < cid.length; i++) {
    cid[i][1] = cid[i][1] * 100;
  }

  console.log(price);
  console.log(cash);

  console.log(cid);
}

console.log(
  checkCashRegister(19.23, 200, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])
);

And here is the output to the console:

>> 1923
>> 20000
>> Array(9)
0: (2) ['PENNY', 101]
1: (2) ['NICKEL', 204.99999999999997]
2: (2) ['DIME', 310]
3: (2) ['QUARTER', 425]
4: (2) ['ONE', 9000]
5: (2) ['FIVE', 5500]
6: (2) ['TEN', 2000]
7: (2) ['TWENTY', 6000]
8: (2) ['ONE HUNDRED', 10000]
length: 9
[[Prototype]]: Array(0)

Everything seems to work as planned, except for the one value, "Nickel" at position [1] in the array.

I really appreciate any advice on this... or if anyone could shine some light about why this specific value is playing up. Thanks. Any help is greatly appreciated.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64

0 Answers0