I wrote a c# "Ground Station" app that sends serial commands to a Nano powered 2ft model ship. One particular command arrives in the format "48.858093,2.294694"
I parse out the ',' delimiter and have a resulting latitude & longitude as String values.
I'm using TinyGPS++ which expects lat/long as a double, and I searched and searched, but couldn't find a way to convert a String to a double with a precision of more than two. So I came up with this mess. It works, but it feels horribly messy, and slow. What's a better method to convert a String to a double?*
double stringToDouble(String str)
{
double result = 0;
int pos = str.indexOf('.');
String integ = str.substring(0,pos);
int integral = integ.toInt();
String sFrac = str.substring(++pos);
double fractional = sFrac.toDouble(); // int borked at larger values. Maybe use long here instead.
int multiplier = sFrac.length();
double frac = fractional/pow(10,multiplier);
if (integral > 0)
{
result = integral + frac;
}else
{
result = integral - frac;
}
return result;
}
Having got this far, I've realised the "proper/fastest method" for my purpose would probably be to stop using strings to send commands and use something a bit more low level like manipulating bits or bytes. However, that's currently a bit beyond my ability and would require a huge c# & arduino command interface rewrite, which I'd rather avoid if possible.
If you can change to using C style strings you can use the strtod() function. Dogma on the forum here is to avoid the String class like the plague anyway. If you are wedded to String, then you can use this as an intermediary step.
You might be interested in my NeoGPS library. It's smaller, faster, more reliable and more accurate than all other GPS libraries, and the examples are properly structured. It's available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries. Even if you don't use it, there is lots of information on the Installation and Troubleshooting pages.
Specifically, NeoGPS retains more significant digits (10) than other libraries (~7), so if you really want the full precision reported by your device, take a look. The distance and bearing calculations in the Location class use these extra digits in their calculations, making the results much more accurate than the naive implementations in other libaries. This is especially important at small distances (<1km).
Thanks for the code, and further reading. I'm too far down this path to not see it through. When I do finally realise why I shot myself in the foot, I'll humbly limp back for NeoGPS. Much appreciated.