String to float/double conversion GPS coordinates

Hi,

I’m getting GPS coordinates from another webpage as a String --> converting it into a float. I’ve been able to do this conversion…However, the float gets rounded off to two decimal places. I know float has more precision… wondering what I’m missing. Is there a better way to do this conversion… I would ideally like to convert it to a double but wasn’t sure how to do it…?

float lat = 0;
float longit = 0;
float latVal = 0;
float longVal = 0;

float parse(String command){
   String latitude = getValue(command, '~', 0);
   String longitude = getValue(command, '~', 1);
   char tarray[longitude.length() + 1];
  //Serial.println(longitude.length()+1);
  longitude.toCharArray(tarray, sizeof(tarray));
   longVal = atof(tarray);
   Serial.println(longVal);
    return longVal;

}

Monitor return:

Actual coordinate:

@bko I read your post on this and adapted part of the code to my purpose(thank you!). Might you have any idea what’s going wrong?

You could try using this instead? Not sure if that’ll make a difference though.
https://docs.particle.io/reference/firmware/photon/#tofloat-

1 Like

Hi @lolkajj

The problem is in print/println–default for floats and doubles is 2 decimal places. Try passing the number of digits you want to print to the println function:

Serial.println(longVal, 12);

Everywhere you have float in your code you could have written double for more precision if you need it. The atof() function does return double which your code is casting to float.

1 Like

Thank you so much! It worked!

1 Like

Thank you for the suggestion! This worked as well though as a different approach to the code rather than the Serial printing problem(which I fixed as per bko’s response).

1 Like