2

我是 C++ 新手,正在为一段代码苦苦挣扎。我在对话框中有一个静态文本,我想在单击按钮时对其进行更新。

double num = 4.7;
std::string str = (boost::lexical_cast<std::string>(num));
test.SetWindowTextA(str.c_str());
//test is the Static text variable

但是文本显示为 4.70000000000002。我如何使它看起来像4.7。

我使用.c_str()了,否则cannot convert parameter 1 from 'std::string' to 'LPCTSTR'会引发错误。

4

3 回答 3

7

这里的使用c_str()是正确的。

如果您想更好地控制格式,请不要boost::lexical_cast自己使用和实现转换:

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

或者,如果您需要将字符串设置为窗口文本之外的字符串,如下所示:

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());
于 2013-10-02T11:39:35.040 回答
2

为什么要把事情搞得这么复杂?使用char[]sprintf完成工作:

double num = 4.7;
char str[5]; //Change the size to meet your requirement
sprintf(str, "%.1lf", num);
test.SetWindowTextA(str);
于 2013-10-02T12:17:56.403 回答
1

没有 double 类型的 4.7 的精确表示,这就是你得到这个结果的原因。在将其转换为字符串之前,最好将该值四舍五入到所需的小数位数。

于 2013-10-02T11:40:30.553 回答