2013-10-02 101 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

相關問題