2015-02-10 69 views
0

我試圖將字符串轉換爲加倍,但未能如願......C#轉換爲字符串倍增

我試圖模擬一個虛擬的代碼是我的應用程序的一部分,該文本值來自我沒有控制權的第三方應用程序。

我需要將以通用格式「G」表示的字符串轉換爲雙精度值並在文本框中顯示。

 string text = "G4.444444E+16"; 
     double result; 

     if (!double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out result)) 
     { 
     } 

我試圖改變的NumberStyles和CultureInfo的,但仍是結果總是返回0所說的其實是錯誤的代碼?

+0

你嘗試'System.Globalization.NumberStyles.Float'? – Rohit 2015-02-10 14:17:04

+3

相關? http://stackoverflow.com/questions/3879463/parse-a-number-from-exponential-notation - 你可能需要先修剪掉'G'。 – Corak 2015-02-10 14:17:30

+0

那爲什麼那邊那邊呢? – virusrocks 2015-02-10 14:22:07

回答

0

剛剛擺脫這種"G"

string text = "G4.444444E+16"; 
    string text2 = text.SubString(1); // skip first character 
    double result; 

    if (!double.TryParse(text2, NumberStyles.Any, 
     CultureInfo.InvariantCulture, out result)) 
    { 
    } 
0

下面是詳細信息:

 Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU"); 

     // if input string format is different than a format of current culture 
     // input string is considered invalid, unless input string format culture is provided as additional parameter 

     string input = "1 234 567,89"; // Russian Culture format 
     // string input = "1234567.89"; // Invariant Culture format 

     double result = 9.99; // preset before conversion to see if it changes 
     bool success = false; 

     // never fails 
     // if conversion is impossible - returns false and default double (0.00) 
     success = double.TryParse(input, out result); 
     success = double.TryParse(input, NumberStyles.Number, CultureInfo.InvariantCulture, out result); 

     result = 9.99; 
     // if input is null, returns default double (0.00) 
     // if input is invalid - fails (Input string was not in a correct format exception) 
     result = Convert.ToDouble(input); 
     result = Convert.ToDouble(input, CultureInfo.InvariantCulture); 

     result = 9.99; 
     // if input is null - fails (Value cannot be null) 
     // if input is invalid - fails (Input string was not in a correct format exception) 
     result = double.Parse(input); 
     result = double.Parse(input, CultureInfo.InvariantCulture);