I'm trying to convert a string into a double but my double gets cut off at the 3rd decimal point.
My string looks like this: "-122.39381636393" After it gets converted it looks like this: -122.394
void setLongitude(string longitude){
this->longitude = (double)atof(longitude.c_str());
cout << "got longitude: " << longitude << endl;
cout << "setting longitude: " << this->longitude << endl;
}
Output example:
got longitude: -122.39381636393
setting longitude: -122.394
I want it to maintain all the decimal points, any tips?
I would write this code if I were you:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "-122.39381636393";
std::cout.precision(20);
cout << "setting longitude: " << stod(str) << endl;
return 0;
}
Basically, you would change things like:
precision for the printing
stod rather than low-level operation to get the double back from the string.
You can see it on ideone running.
It is probably the printing that is truncating precision, not the conversion from string to double.
Look at ios_base::precision http://www.cplusplus.com/reference/ios/ios_base/precision/
e.g.
cout.precision(10);
cout << "setting longitude: " << this->longitude << endl;
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