Search code examples
c++precisionstringstream

stringstream loses precision while converting


I have a small problem with stringstream. It loses precision when I use it to convert string to double.

const std::string str = "44.23331002";
double x;
stringstream ss;
ss << str;
ss >> x;
cout << str << " = " << x << endl;

The output is: 44.23331002 = 44.2333

Why is this? Does it convert to float and has limited digit precision?


Solution

  • You need to set the precision on the output stream:

    #include <iostream>
    #include <sstream>
    #include <iomanip>
    using namespace std;
    
    int main() {
        const std::string str = "44.23331002";
        double x;
        stringstream ss;
        ss << str;
        ss >> x;
        cout << str << " = " << std::setprecision(10) << x << endl;
    }
    

    Output:

    44.23331002 = 44.23331002
    

    (Demo)