Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Double conversion C++ [duplicate]

Tags:

c++

string

double

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?

like image 997
jshah Avatar asked Dec 26 '22 09:12

jshah


2 Answers

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.

like image 169
lpapp Avatar answered Jan 01 '23 21:01

lpapp


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;

like image 33
teambob Avatar answered Jan 01 '23 20:01

teambob