2013-10-02 51 views
2

我是C++的新手,正在为一段代码挣扎。我在对话框中有一个静态文本,我想在点击按钮时进行更新。将双精度值格式化为小数点后1位

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

+0

可能重复[?如何“COUT”正确的号码double值的小数位(http://stackoverflow.com/questions/4217510/how -to-cout-the-correct-number-of-decimal-places-of-double-value) – Dariusz

+0

这与'.c_str()'无关! – Dariusz

回答

2

为什么让事情变得如此复杂?使用char[]sprintf做的工作:

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

那么,在这种情况下,为什么不进一步简化,使'num'本身是一个'char'数组,4.7作为字符串文字?这将工作,如果num = 123456?什么是'str'的最佳数组大小是num的值在编译时是未知的? – legends2k

+0

@ legends2k'char str [20]'可以处理'double'和'long long'。它的尺寸并不大,对于C号码类型已经足够了。 – Chen

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

由于一些奇怪的原因,你的答案打印5 .. – Madz

+1

@Madz对不起,这是总nr。的数字,而不是小数(参见任何[参考文档](http://en.cppreference.com/w/cpp/io/manip/setprecision))。所以正确的值是'setprecision(2)'。 – Angew

1

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

+0

**将**转换为字符串时,您的意思是**。就像你刚才所说的那样,没有办法将它精确地*作为数字。* – Angew

+0

有没有办法在转换为字符串时做到这一点?你能解释一下吗? – Madz

+1

@Madz这就是我的答案。 – Angew

相关问题