0

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

Thanks!

3
Contributors
7
Replies
35
Views
3 Years
Discussion Span
Last Post by nathan.pavlovsky
Featured Replies
  • 2

    > 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 … Read More

0

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

Edited by Ancient Dragon

0

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.

2

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();
0

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.

Edited by Ancient Dragon

0

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?

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.