Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting a double value to 1 decimal place

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.

like image 763
Madz Avatar asked Dec 05 '25 20:12

Madz


2 Answers

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());
like image 173
Angew is no longer proud of SO Avatar answered Dec 08 '25 10:12

Angew is no longer proud of SO


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);
like image 45
Chen Avatar answered Dec 08 '25 12:12

Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!