0

enter image description here

In the code, lat and lng are initialized as number types, but why does it become string when you put it in an object? I want the coordinate values to be numbers. What can I do?

ex) lat: "35.87" -> lat: 35.87

let lat_tmp = 0;
let lng_tmp = 0;
const lat_lng = [];
let lat_tmp = 0;
let lng_tmp = 0;
let arr_tmp = [
  {
    lat: 0,
    lng: 0,
  },
];
let idx = 0;
function successFunction(data) {
  var allRows = data.split(/\r?\n|\r/);
  for (var singleRow = 1; singleRow < allRows.length; singleRow++) {

    var rowCells = allRows[singleRow].split(',');
    for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
      if (rowCell === 3) {
        lat_tmp = rowCells[rowCell];
      } else if (rowCell === 4) {
        lng_tmp = rowCells[rowCell];
      }
    }
    arr_tmp = [{ lat: lat_tmp, lng: lng_tmp }];
    lat_lng[idx] = arr_tmp;
    idx += 1;
  }
  console.log(lat_lng);
}

1 Answer 1

3

You're splitting a string, so each element of the result will also be a string. You can use the unary plus operator or parseFloat to convert them into numbers.

var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
    if (rowCell === 3) {
        lat_tmp = +rowCells[rowCell];
    } else if (rowCell === 4) {
        lng_tmp = +rowCells[rowCell];
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

unary plus is one option, however, for code readability, I would go with something like parseInt
@Cjmarkham In this case, it would be parseFloat. I've added that to my answer.

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.