1

Im trying to convert a value to float, that i get from an array, but it always comes out as NaN, even though it starts with a number. What am i doing wrong?

var lat = <?php echo json_encode($result1); ?>;
for(var i = 0; i<lat.length; i++){
    //var lokacija = {lat: parseFloat(lat[i]), lng: parseFloat(lng[i])};
    //var marker = new google.maps.Marker({position: lokacija, map: map}); 
    var num2 = lat[i];
    console.log(lat[i]);
    console.log(parseFloat(num2)
}

In console it comes out like this(array has tvo values in it): https://i.gyazo.com/31d5e613a7abee5f86daa52895561b5d.png

1
  • try console.log(parseFloat(num2.lat)) Commented Jan 23, 2019 at 19:00

3 Answers 3

1

It looks like you have an array of objects from which you need the lat property:

var arr = <?php echo json_encode($result1); ?>;
for (var i = 0; i < arr.length; i++){
  var num2 = arr[i].lat;
  console.log(parseFloat(num2);
}

A more modern way of approaching this:

arr.forEach(({ lat }) => console.log(parseFloat(lat));
Sign up to request clarification or add additional context in comments.

Comments

1

Because you pass object which contains {lat: "46.14...."}

Try to pass lat[i].lat into parserFloat function.

or in your code:

   var lat = <?php echo json_encode($result1); ?>;
   for(var i = 0; i<lat.length; i++){
     //var lokacija = {lat: parseFloat(lat[i]), lng: parseFloat(lng[i])};
     //var marker = new google.maps.Marker({position: lokacija, map: map}); 
     var num2 = lat[i].lat;
     console.log(lat[i]);
     console.log(parseFloat(num2));
}

and some tip for future - always specify radix parameter (10 usually) to avoid any kind of unexpected behavior like: parseFloat('010') (which is octal) will return 8, but not expected 10.

Comments

0

Your array contains a bunch of objects, so you need to access the properties of each object appropriately. You can use ES6 object destructuring as one way to achieve this (by naming your variable the same thing as the property you're trying to access from the object)

var lats = [{
  lat: "46.14949843"
}, {
  lat: "-21.20654846"
}];


for (var i = 0; i < lats.length; i++) {
  const {
    lat
  } = lats[i];
  console.log(parseFloat(lat));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.