Hello Programmers! How can I convert a double to a string without losing its precision (i.e. values after the decimal point)?

Thanks!

Recommended Answers

All 7 Replies

how many digits after the decimal point do you want? You can use sprintf() to do it. See this article

double n = 1.234678901234567890;
char str[10];
sprintf(str,"%.5f", n);

I want two digits after the decimal point when the double is converted to a string. How can I do it with sprintf()? Before I posted here, I scoured the internet all over, and all the explanations for sprintf were to complicated. I couldn't understand.

How can I do it with sprintf()? Before I posted here, I scoured the internet all over, and all the explanations for sprintf were to complicated. I couldn't understand.

If AD's example above was too complicated, I'm not sure what to tell you, because that's as simple as it gets. For your specific needs:

double n = 1.23456;
char s[10];

sprintf(s, "%.2f", n);

In C++ there are many more options, but I suspect those will confuse you as well. The usual solution involves stringstreams:

double n = 1.23456;
ostringstream oss;

oss.precision(2);
oss << fixed << n;

string s = oss.str();

In sprintf(), the "%.5f" says to print a double (that's what the 'f' means) with 5 digits following the decimal point. So if you only want 2 digits then just change the 5 to a 2.

I don't want a c-style string. I want a regular class <string> string that is stored in a var., not printed. How can I do that?

How can I do that?

You could actually read this thread instead of guessing at what people are saying. I posted how to do it with std::string.

Thank you! I was careless. Problem solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.