2012-08-14 33 views
0

我想知道如何將像"1234.123456"這樣的字符串轉換爲doublefloat。 我需要至少3位精度(即小數點後的3位數字,無論位於點之前的位數)。如何在C++中將字符串轉換爲具有6位精度的double?

+1

'用於總共縮放它的6位數的雙倍使用',O_o – Gir 2012-08-14 08:32:51

+0

['std :: stof'](http://en.cppreference.com/w/cpp/string/basic_string/stof)或['strtof'](http://en.cppreference.com/w/cpp/串/字節/ strtof)。 – 2012-08-14 08:33:59

+0

我的編譯器告訴我, double d = 1234.123456 \t cout << d << endl; 輸出:1234.12 – MiNdFrEaK 2012-08-14 08:34:37

回答

6

精確值1234.123456不能用任何通常的 機器浮點格式表示。你所能做的就是選擇你需要多少精度,並使用它。 (在大多數現代機器,double有 16位精度,但仍然不意味着所有16位 值精確表示。)

至於轉換,只是做你會做轉換任何類型是什麼:

std::istringstream s("1234.123456"); 
double d; 
s >> d; 

而且讀 http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html。爲了安全地使用 機器浮點數,它將解釋你需要知道的基本最小值。

0
#include<stdlib.h> 

int main() 
{ 
    double dnum = atof("1234.123456") ; 

    printf ("%f\n" , dnum) ; 

    return 0 ; 
} 
相關問題