user3154754
user3154754

Reputation: 35

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.

Upvotes: 2

Views: 5522

Answers (3)

Pyves
Pyves

Reputation: 6483

If you want to get the full precision of your double without limiting it to a specific value (implied by your "occasionally need more than six decimal places"), and if you are using the Boost libraries, you can also try this following alternative:

#include <boost/lexical_cast.hpp>    
#include <iostream>

using namespace boost;
using namespace std;    

int main() {
    double var = 1.0000001;   
    cout << lexical_cast<string>(var) << endl;
    return 0;
}

This has proven useful in one of my applications where precision did matter, and where the std::stringstream approach was not very convenient and elegant due to usage of some specific logging function wrappers. You can find more information about boost::lexical_cast and how it deals with internal representations here.

Obviously, if you are not currently using Boost in your project, this approach is overkill.

Upvotes: 2

abrahamhs
abrahamhs

Reputation: 101

try this:

#include <sstream>
#include <string>

// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

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;
}

Upvotes: 5

Related Questions