1

I'm having some trouble with the JavaScript indexOf() Method. I have an array...

      pointLatArray = new Array();

When I try to get the index of a variable that I know is present in the array it returns -1, which I know normally indicates to the value not being found. When my code is as follows..

      setlat = 52.6688391881732;
      pointArrayIndex = pointLatArray.indexOf(setlat);
      console.log(setlat + " " + pointLatArray[8] + " " + pointArrayIndex); 

I get the following logged to console.....

       04-16 12:35:31.370: D/CordovaLog(7048): 52.6688391881732 52.6688391881732 -1

However when I change the code by replacing setlat with pointLatArray[8] in the following line....

      pointArrayIndex = pointLatArray.indexOf(pointLatArray[8]);

the following gets logged to console where it displays the correct index of 8 instead of -1 as expected.......

      04-16 12:46:17.230: D/CordovaLog(8497): 52.6688391881732 52.6688391881732 8

Is it because I'm using such a long decimal set as the variable setlat? If so, or for what ever reason if anyone could suggest a fix I would appreciate it very much.

Many thanks

hotshots
  • 113
  • 4
  • 16

1 Answers1

2

Strict comparison for double numbers is not a good idea. Probably what you observe here is rounding error. Although the numbers seem to be the same to you they may differ by a small epsylon.

One option I see is to use custom indexOf function using epsylon comparison(i.e. allow numbers to differ by a small value. For instance 0.000000000001 or 1e-12).

Community
  • 1
  • 1
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176