0

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.

3 Answers 3

2

Here's a reference for to_string. Note that it produces "As many digits are written as needed to represent the integral part, followed by the decimal-point character and six decimal digits".

The rest of the question is a dupe of lots of SO ansers - see here, for example.

Sign up to request clarification or add additional context in comments.

Comments

0

I believe what you are looking for is std::fixed which is described below: http://www.cplusplus.com/reference/ios/fixed/

Comments

0

Using ostringstream will solve your problem.

#include <sstream>

double var = 1.0000001;
ostringstream os;
os << setprecision(10) << var;
string str = os.str();
cout << str << endl; // this should print 1.0000001

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.