convert double to string query

J

jeff_zhang446

Hi,

I try to convert double to string as below:


std::string cnvrtToString(double lValue)
{
std::eek:stringstream lStream;
lStream << lValue;
return lStream.str();
}

however I found that I have lost the accuracy(having lesser decimal
value) of my result after I print it to an outfile by doing
fprintf(File, "%s", stream.ctr());

I am not able to print directly:
fprintf(File, "%f", lValue); as I need to format my outfile
appropriately.

I wonder if the lost of accuracy happen when I convert double to
string? If yes, is there anyway I can avoid that?

Please correct me if I am wrong.

Thnak you.

jeff
 
V

Victor Bazarov

I try to convert double to string as below:


std::string cnvrtToString(double lValue)
{
std::eek:stringstream lStream;
lStream << lValue;
return lStream.str();
}

however I found that I have lost the accuracy(having lesser decimal
value) of my result after I print it to an outfile by doing
fprintf(File, "%s", stream.ctr());

I am not able to print directly:
fprintf(File, "%f", lValue); as I need to format my outfile
appropriately.

I wonder if the lost of accuracy happen when I convert double to
string? If yes, is there anyway I can avoid that?

Using your terms, yes, it does. The default "accuracy" is 6 digits
after the decimal point. If your value is around 1, you lose more
than half the digits. You need 'setprecision(16)' (for most double
representations out there).

V
 
J

jeff_zhang446

could you please explain in more detail how and where to include the
setprecision?

thanks

jeff
 
M

Mike Wahler

could you please explain in more detail how and where to include the
setprecision?

Insert it into the stream.

#include <iomanip>
#include <iostream>

int main()
{
double d(1.23456789);
std::cout << std::setprecision(16);
std::cout << d << '\n';
return 0;
}

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top