将double值格式化为1位小数

时间:2013-10-02 11:34:49

标签: c++ string visual-c++ boost

我是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'错误。

3 个答案:

答案 0 :(得分: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());

答案 1 :(得分:2)

为什么让事情如此复杂?使用char[]sprintf完成工作:

double num = 4.7;
char str[5]; //Change the size to meet your requirement
sprintf(str, "%.1lf", num);
test.SetWindowTextA(str);

答案 2 :(得分:1)

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