user3154754 user3154754 - 3 months ago 11
C++ Question

Loss of Precision when Converting Double to String in C++

So I know

setprecision(int n)
should be used when printing a double value with precision
n
. However, I've run into a problem on a project that I'm working on that is akin to this code:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
double var = 1.0000001;
cout << setprecision(10)<< var << endl;
string str = to_string(var);
cout << str << endl;
return 0;
}


Here is the output:

1.0000001
1.000000


In the project I'm working on, I need to save the double value as a string, and it will occasionally need more than six decimal places of precision. Here, precision is clearly lost in the conversion. Any pointers would be greatly appreciated.

Answer

You can use std::stringstream.

#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

int main(void) {
    double var = 1.0000001;
    cout << setprecision(10)<< var << endl;
    stringstream ss;
    ss << setprecision(10) << var;
    string str;
    ss >> str;
    cout << str << endl;
    return 0;
}