【问题标题】:C# converting a string to doubleC#将字符串转换为双精度
【发布时间】:2015-04-10 14:42:11
【问题描述】:

我正在尝试将字符串转换为双精度但无法这样做...

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

我需要将以通用格式“G”表示的字符串转换为双精度值并在文本框中显示。

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

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

我尝试通过更改 numberstyles 和cultureinfo,但结果始终返回 0。建议代码有什么问题?

【问题讨论】:

  • 你试过System.Globalization.NumberStyles.Float 吗?
  • 相关? stackoverflow.com/questions/3879463/… - 您可能需要先修剪掉 'G'
  • 对了,为什么那个 G 在那里?
  • @virusrocks - 它的general format specifier。这个字符串是从哪里来的?如果你想解析它,似乎你需要删除“G”,但最好看看你是否可以改变它的来源

标签: c# string type-conversion double tryparse


【解决方案1】:

摆脱这个"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))
    {
    }

【讨论】:

    【解决方案2】:

    这里有更多细节:

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

    【讨论】:

      猜你喜欢
      • 2013-10-10
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      相关资源
      最近更新 更多