2

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.

Dariusz
  • 21,561
  • 9
  • 74
  • 114
Madz
  • 1,273
  • 2
  • 18
  • 35
  • possible duplicate of [How to 'cout' the correct number of decimal places of a double value?](http://stackoverflow.com/questions/4217510/how-to-cout-the-correct-number-of-decimal-places-of-a-double-value) – Dariusz Oct 02 '13 at 12:20
  • This has nothing to do with `.c_str()`! – Dariusz Oct 02 '13 at 12:21

3 Answers3

7

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());
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

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);
Chen
  • 1,170
  • 7
  • 12
  • Well, in that case, why not simplify even further and make `num` itself a `char` array and 4.7 as string literal? Will this work if num = 123456? What would be the optimal array size of `str` is the value of num is not known at compile time? – legends2k Oct 03 '13 at 08:11
  • @legends2k `char str[20]` can handle `double` and `long long`. It's not big size and already enough for C number types. – Chen Oct 03 '13 at 09:17
1

There is no exact representation of 4.7 with type double, that's why you get this result. It would be best to round the value to the desired number of decimal places before converting it to a string.

helb
  • 7,609
  • 8
  • 36
  • 58