I'm new to C++ and am struggling with a piece of code. I have a Static text in a dialog, which I want to update on button click.
double num = 4.7;
std::string str = (boost::lexical_cast<std::string>(num));
test.SetWindowTextA(str.c_str());
//test is the Static text variable
However the text is displayed as 4.70000000000002. How do I make it look like 4.7.
I used .c_str() because otherwise a cannot convert parameter 1 from 'std::string' to 'LPCTSTR' error gets thrown.
Use of c_str() is correct here.
If you want finer control of the formatting, don't use boost::lexical_cast and implement the conversion yourself:
double num = 4.7;
std::ostringstream ss;
ss << std::setprecision(2) << num; //the max. number of digits you want displayed
test.SetWindowTextA(ss.str().c_str());
Or, if you need the string beyond setting it as the window text, like this:
double num = 4.7;
std::ostringstream ss;
ss << std::setprecision(2) << num; //the max. number of digits you want displayed
std::string str = ss.str();
test.SetWindowTextA(str.c_str());
Why make things so complicated? Use char[] and sprintf to do the job:
double num = 4.7;
char str[5]; //Change the size to meet your requirement
sprintf(str, "%.1lf", num);
test.SetWindowTextA(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With