0

I'm working on a Javascript project and I've run into an issue, and I'm not sure why it's happening. Basically I'm using setInterval to set the value of a variable between 0 and 1 in increments of 0.05 (so the value goes 0, 0.05, 0.1 ... 1, then back down to 0, and then it repeats) like so:

let t = 0;
let reverse = false;

let someInterval = setInterval(function(){
  if(reverse == false){
      t+= 0.05;
      if(t>1){
          reverse = true;
      }
  } 

  if(reverse){
      t-=0.05;
      if(t<0){
          reverse = false;
      }
  }

  console.log(t);
}, 500)

and it basically works except that when t goes from 0.05 to 0 the console logs its value as -9.71445146547012e-17 and I can't figure out why. I'm not super knowledgeable on programming stuff so I'm not sure if I've done something wrong or if this is just a weird Javascript bug. Either way if anyone has some insight as to why this is happening it would be very much appreciated. Thank you :)

Fred
  • 1
  • 1
    It's not large negative number - it's one of the smallest ones representable in JS. ) Check [this thread](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) for some explanation; spoiler alert: `0.15 - 0.05 !== 0.1` – raina77ow Oct 03 '20 at 15:25
  • 1
    And you're not wondering about those other "strange" numbers at all? – Andreas Oct 03 '20 at 15:27
  • The short answer would be "floating point". Read more about that. – Danilo Ivanovic Oct 03 '20 at 15:29

0 Answers0