C#将字符串转换为double

时间:2015-02-10 14:14:02

标签: c# string type-conversion double tryparse

我正在尝试将字符串转换为double但无法将其转换为...

我试图模拟一个虚拟代码,它是我的应用程序的一部分,文本值来自我无法控制的第三方应用程序。

我需要转换以通用格式表示的字符串" G"到一个double值并在文本框中显示。

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

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

我尝试通过更改numberstyles和cultureinfo但结果总是返回0.建议代码有什么问题?

2 个答案:

答案 0 :(得分: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))
    {
    }

答案 1 :(得分: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);
相关问题