Converting String to floating number using toFloat()

void setup() {
  Serial.begin(9600);
}

void loop() 
{
 String inputString;
 inputString.reserve(100);
 inputString = "01:36:59  $GNGGA,013659.00,3402.77961,N,11750.73009,W,1,10,1.87,222.2,M,-32.3,M,,*7C";
 inputString.remove(12,1);
int index1 = inputString.indexOf(",N"); // Find the index of "N"
int index2 = inputString.indexOf(",W"); // Find the index of "W"

// Extract the latitude value and convert it to a float
String latString = inputString.substring(index1-10, index1);
Serial.println(latString);
float latitude = latString.toFloat();
// Extract the longitude value and convert it to a float
String lonString = inputString.substring(index2-11, index2);
float longitude = lonString.toFloat();
Serial.println(lonString);

// Print the latitude and longitude values
Serial.print("Latitude:");
Serial.println(latitude, 5);
Serial.print("Longitude:");
Serial.println(longitude, 5);
}

In theory this code should parse through the string and extract the values before the N and W which are latitude and longitude values. However when converting the string to a float using toFloat() it changes the last two decimals places. I checked to see if I was parsing through the string correctly by printing the strings individually, so I'm kinda lost as to why the value changes when it gets converted.

Because floats have only 5-6 significant digits.

Is there a way to have more significant digits?

On 32 bit processors like the ESP32 you could use double.

Is there any other way to solve it within the arduino IDE?

It is not a matter of the IDE, ESP32 are supported.

You could parse the integral and the fractional part into separate variables.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.