Madz
Madz

Reputation: 1279

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.

Upvotes: 2

Views: 3713

Answers (3)

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

Upvotes: 7

Chen
Chen

Reputation: 1180

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

Upvotes: 2

helb
helb

Reputation: 7793

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.

Upvotes: 1

Related Questions