By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,738 Members | 1,461 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,738 IT Pros & Developers. It's quick & easy.

convert double to string query

P: n/a
Hi,

I try to convert double to string as below:
std::string cnvrtToString(double lValue)
{
std::ostringstream 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

Sep 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
je***********@yahoo.com wrote:
I try to convert double to string as below:
std::string cnvrtToString(double lValue)
{
std::ostringstream 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
Sep 23 '05 #2

P: n/a
could you please explain in more detail how and where to include the
setprecision?

thanks

jeff

Sep 24 '05 #3

P: n/a

<je***********@yahoo.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
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
Sep 24 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.