2013-11-25 30 views
1

我一直在試圖將double轉換爲不帶C++ 11(ToString)的字符串,但它只接受小數的數目爲5作爲默認值。我該如何改變它?將double轉換爲保持數字高精度的字符串,C++

的命令是:

string a = static_cast<ostringstream*>(&(ostringstream()<<digits))->str(); 

,但會將5位小數,而我想創造出具有所有小數字符串(例如100) 我知道,很多小數不要無所謂。這是我正在做的練習的一點。

有什麼建議嗎?

非常感謝您的時間 乾杯!

+2

您shuold閱讀[戈德堡(http://docs.oracle.com/cd/E19957-01/806-356 8/ncg_goldberg.html),然後重新考慮您的問題,一旦您確定了可以從(* binary *)'double'中提取多少有意義的*十進制*數字。 – BoBTFish

+0

_「all the decimals(eg 100)」_ lolwut –

回答

5

使用IO操作器setprecision這裏std::cout但它只是對stringstream

// setprecision example from cplusplus.com 
#include <iostream>  // std::cout, std::fixed 
#include <iomanip>  // std::setprecision 

int main() { 
    double f =3.14159; 
    std::cout << std::fixed << std::setprecision(9) << f << '\n'; 
    return 0; 
} 

順便說一句,沒有double將有100 meaningfull位,這是15或17,我忘了到底有多少。

編輯:我忘了,如果你能使用C++ 11 ...你可以(也應該)使用to_string

#include <string> 

// ....  
std::string f_str = std::to_string(f); 
+0

謝謝Johan,你說的很多數字他們沒有用,所以讓我們看看把15位數字放到字符串中 – thahgr

+2

我明確表示我不能使用C + +11 .....所以這怎麼可以用stringstream – thahgr

+0

@thahgr:答案已經告訴你在你的'std :: stringstream'上使用I/O操縱符,就像'std :: cout'中所演示的那樣。 –

0

這爲我工作終於

 digits = 1.12345123451234; 
     char buff[100]; 
     sprintf(buff, "%1.14f", digits); 
     string a(buff); 

感謝您檢查它在任何情況下

乾杯

+0

爲什麼你分配這麼多的緩衝區? –

相關問題