Anders Iversen
Anders Iversen

Reputation: 23

JSON.parse fails for negative floating point numbers

I have a simple script like this:

request = $.ajax({
          url: "/getmesomefloats.php",
          type: "post",
        });

        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log(response, textStatus);
            if(textStatus == 'success') {
              console.log($.parseJSON(response);
            }
        });

Where getmesomefloats.php looks like this:

  $points[] = array(-14.27664,-170.6878);
  $points[] = array(-16.29323,-165.3741);
  $points[] = array(-15.86157,-162.7885);
  $points[] = array(-15.89847,-160.2066);
  echo json_encode($all_points);

the first console log call spits out this string:

[[-14.27664,-170.6878],[-16.29323,-165.3741],[-15.86157,-162.7885],[-15.89847,-160.2066]] success

The $.parseJSON (or JSON.parse(response)) spits out this ("expanded" in the console):

[Array[2], Array[2], Array[2], Array[2]]
  0: Array[2]
    0: -1589268.2950388812
    1: NaN
    length: 2
    __proto__: Array[0]
  1: Array[2]
    0: -1813754.066977689
    1: NaN
    length: 2
    __proto__: Array[0]
  2: Array[2]
    0: -1765701.8955818643
    1: NaN
    length: 2
    __proto__: Array[0]
  3: Array[2]
    0: -1769809.5847921362
    1: NaN
    length: 2
    __proto__: Array[0]
  length: 4
  __proto__: Array[0]

I don't understand why I get the NaN's and why eg -14.27664 is converted to -1589268.2950388812 ? What should I do to get the correct values? Are the floating point numbers to much to handle for javascript? Bonus info: The floats are GPS coordinates, and I ('m going to) use them in a map script not included here.

Upvotes: 2

Views: 9612

Answers (2)

HardlyNoticeable
HardlyNoticeable

Reputation: 517

I had an issue with parsing negative values from some data I copy/pasted from wikipedia. It turned out that the minus sign was the wrong character (ascii decimal 150 instead of 45).

Upvotes: 3

drs9222
drs9222

Reputation: 4508

There is nothing in [[-14.27664,-170.6878],[-16.29323,-165.3741],[-15.86157,-162.7885],[-15.89847,-160.2066]] given that JavaScript can't handle.

Output

Maybe you could try including the raw output from your request in case there is something I can't see in the console.log output you gave.

Upvotes: 0

Related Questions