I am having trouble converting a string to a double. I am given a string with lat/long coordinates in the format of 33.9425/N 118.4081/W
I first call my function trimLastChar(std::string& input)
twice, which will remove the the North, South, East, West characters and then the forward slash. This function correctly returns 33.9425
and 118.4081
respectfully as a std::string
.
I am using the following code to convert my std::string
to a double
...however the problem is, the conversion losses precision -- I suspect it gets rounded?.
// Location In String is what trimLastChar returns
std::stringstream stream(locationInString);
std::cout << "DEBUG: before: " << locationInString << " ";
// output is a double* output = new double passed by reference to my function
stream >> output;
std::cout << output << std::endl;
The output in this case would produce:
33.9425
118.408
As you notice, the correct value should be 118.4081
but the 1 is missing...
Any ideas how to fix? Or more important, why is this happening?
The precision wasn't lost on input. It's being lost on output.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
double v = 118.4081;
cout << v << endl;
cout.precision(10);
cout << v << endl;
}
outputs:
$ g++ -Wall x.cpp && ./a.out
118.408
118.4081
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With