Reputation:
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.
Upvotes: 0
Views: 176
Reputation: 10261
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.
Upvotes: 2
Reputation: 962
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
Upvotes: 0
Reputation: 1
I believe what you are looking for is std::fixed which is described below: http://www.cplusplus.com/reference/ios/fixed/
Upvotes: 0