0
var startX = 501;
var finalX = 320;
var multiply = .01;
var res = finalX - startX;
var extract = multiply * res;
var toEval;

if (res > 0) {
  toEval = "<=";
} else {
  toEval = ">=";
}
console.log("extract= " + extract + "");

while (eval(startX + toEval + finalX)) {

  startX += (-1.81);
  console.log(startX + " " + extract);

}

the "problem" is in the while loop, in the thirteenth iteration happen this in console:

  1. 482.9 -1.81
  2. proof2.html:39 481.09 -1.81
  3. proof2.html:39 479.28 -1.81
  4. proof2.html:39 477.46999999999997 -1.81
  5. proof2.html:39 475.65999999999997 -1.81

479.28 - 1.81 = 477.47

so what is really happen in the loop?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
G. Jaen
  • 13
  • 1

1 Answers1

2

You could use a function for the comparing, instead of an use of eval.

var startX = 501,
    finalX = 320,
    multiply = .01,
    res = finalX - startX,
    extract = multiply * res,
    toEval;

if (res > 0) {
    toEval = function (a, b) { return a <= b; };
} else {
    toEval = function (a, b) { return a >= b; };
}
console.log("extract= " + extract + "");

while (toEval(startX, finalX)) {
    startX += (-1.81);
    console.log(startX + " " + extract);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Really helpful, thanks. but my questios is there, why is javascript machine using so mani decimals matematicaly wrong 479.28 - 1.81 = 477.47 not 477.46999999999997 i know that i could round() some way but... what happen? – G. Jaen Jul 12 '16 at 19:58
  • 1
    you may have a look here [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken). It's matter of storing a floating-point number and their calculation. – Nina Scholz Jul 12 '16 at 20:01
  • totally helpful, i am new programming, so cloud you give me some guide or videos to watching. i really want to learn now am reading "speaking javascript". Thank you. – G. Jaen Jul 14 '16 at 07:07
  • sorry, i do not now any videos. just the documentation of [mozilla](https://developer.mozilla.org/en-US/docs/web/javascript/reference), which is very helpful. but if aou have questions, the just ask at so. – Nina Scholz Jul 14 '16 at 07:10