Why is this an infinite loop?!

I’m in the early stages of breaking down the Exact Change exercise. I’ve written the following code that works sometimes but gives me an infinite loop other times based on the changeDue var.

var registerVals = [100, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01];
  var changeDue = 0.60;
  var changeGiven = [];
  
  
  while (changeDue > 0) {
  for (var i = 0; i < registerVals.length; i++) {
      if (changeDue - registerVals[i] >= 0) {
        changeGiven.push(registerVals[i]);
        changeDue -= registerVals[i];
        break;
      }
    }
  }
return changeGiven;

The code I’ve posted will give me an infinite loop. However if I change changeDue = 0.50 I get my expected result of changeGiven = [0.25, 0.25] It also works when change is set at 1, 5, ect. What’s acting up here?!

Open the console and enter:

0.5 - 0.25 - 0.25

What’s the result?

Now enter:

0.6 - 0.25 - 0.25 - 0.1

What’s the result?

This recent thread may help (possible spoilers!!!): https://forum.freecodecamp.com/t/exact-change-exercise-why-the-floating-point-error-and-best-approach-to-subtract-integer-from-floating-point/72376

2 Likes

Because changeDue will always be higher than 0 while being lower than anything in registerVals (ie it can’t subtract to get any lower)

I changed it to continue while console logging changeDue . Every time it finishes the for loop, the final number still tests as being higher than zero.

1 Like

Thank you both for your answers to this. I’ll spare you the majority of my “what’s the point in having computers if they can’t do basic math” rant I just had to myself. It appears that multiplying the decimal by 100 trick should work for me in this context. :slight_smile: