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?

Answers


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)


calcto answered correctly.and You can change precision in two way: std::setprecision(10) and std::cout.precision(10)


Need Your Help

The url is not recognized as a valid Google Script

google-apps-script

I published an App Script as a web app and everything runs fine when I use the web app URL.