簡體   English   中英

C#將字符串轉換為雙精度

[英]C# converting a string to double

我正在嘗試將字符串轉換為雙精度但無法這樣做...

我試圖模擬一個偽代碼,這是我的應用程序的一部分,文本值來自我無法控制的第三方應用程序。

我需要將以通用格式“ G”表示的字符串轉換為雙精度值,並在文本框中顯示該字符串。

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

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

我嘗試通過更改numberstyles和cultureinfo進行嘗試,但結果始終返回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))
    {
    }

這是更多詳細信息:

        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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM