Convert strings to double C ++ conversion

I am trying to convert a string to double, but my double is truncated at the third decimal point.

My line looks like this: "-122.39381636393" After converting it, 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 support all decimal points, any hints?

+4
source share
3 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:

  • print accuracy

  • instead of performing a low-level operation to get a double back from the string.

You can see on ideone running .

+2
source

, , , , double.

ios_base:: precision http://www.cplusplus.com/reference/ios/ios_base/precision/

. cout.precision(10); cout << "setting longitude: " << this->longitude << endl;

+3

++ 11 - stod - String TO Double. , try ... catch , , .

, , atof [ C], double ( Ascii TO Float, double), , precision setprecision, cout, ,

cout << "Setting longitude: " << setprecision(15) << this->longitude << endl;

<iomanip> setprecision.

+1
source

Source: https://habr.com/ru/post/1539132/


All Articles