You are here:

C++/Converting a double to a string...


QUESTION: Hi again Eddie,

I need to enter a double into an edit box. Is there a way to accurately convert a double to a string for this purpose?

Also, is there a way to round off this double to 4 decimal places?

Thanks in advance for your help,


ANSWER: Hello Neil, thank you for the question.

Sure, C++ provides an easy mechanism for this called ostringstream. Here is some sample code:

double d = 0.123456789;
std::ostringstream oss;
oss << d;
std::string value = oss.str();

This inserts the value d into the stream, and then returns the string value by calling .str(), which you can use to display.

Setting the precision is the same as always.

std::cout << setprecision(2) << value << std::endl;

This should do what you're looking for.

I hope this information is helpful.

- Eddie

---------- FOLLOW-UP ----------

QUESTION: Hi again, Eddie,

I'm still having trouble placing this string(value) into the text box. The only reference one of my books on VisualC++ 6 gives is below and doesn't work because: binary '=' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocat.

Is there a better way to enter this std::basic string into an edit box than below?

CString strText;
CEdit* pStrValue = (CEdit*)GetDlgItem(IDC_EDIT_BOX);

Thanks in advance for your help,

Hello Neil, thank you for the question.

From what I understand you have a std::string called value, which contains the double you want to put in the edit box, correct?

I'm not much of a MFC person, however, from what I've read online you should be able to assign a const char* to a CString using the _T macro to translate. I don't know if you know this already so I'll say it. You can get the const char* C style string from a std::string by called .c_str():

CString strText = _T(value.c_str());

That should return the const char* string and translate it to a CString with the _T macro.

There is a link that explains it.

Let me know if this works for you.

I hope this information was helpful.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 All rights reserved.