c# Convert.ToDouble format exception error

前端 未结 4 892
执念已碎
执念已碎 2020-12-07 01:45

I\'m trying to convert this string to double

Convert.ToDouble(\"1.12\");

and this is the output

System.FormatException wa

相关标签:
4条回答
  • 2020-12-07 02:14

    Convert.ToDouble uses Double.Parse internally. If you are unsure of the culture context, you should use an overload of Double.Parse precising the culture:

    double d = double.Parse("1.12", CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2020-12-07 02:32

    You don't have to replace . to ,.. however a better way is to use the .net TryParse method like:

    double d;
    if (double.TryParse("your string data", out d)
    {
        Console.WriteLine(d);
    }
    

    Edit: Also note that by replacing . by , you are getting a wrong results, for instance 1.12:

    double d = double.Parse(1.12);//d will equals to 1.12
    double d = double.Parse(1,12);//d will equals to 112.0
    
    0 讨论(0)
  • 2020-12-07 02:35

    double.Parse will use the current culture by default. It sounds like you want the invariant culture:

    double d = double.Parse("1.12", CultureInfo.InvariantCulture);
    

    EDIT: Just to be clear, obviously you shouldn't use this if you're trying to parse text entered by a user in a different culture. This is for use when you've received data in the invariant culture (as most machine-to-machine data text-based formats are) and want to enforce that when parsing.

    0 讨论(0)
  • 2020-12-07 02:36

    Keep in mind, this problem can depend on where the input string comes from. If it is read from a database as an object, you might solve your problem by keeping it as an object and using Convert.ToDouble() as follows:

    public double Double_fromObject(object obj)
        {
          double dNum = 0.0;
          if (obj.ToString() != string.Empty) // the Convert fails when ""
          {
            try
            {
              dNum = Convert.ToDouble(obj);
            }
            catch (SystemException sex)
            {
              // this class's error string
              LastError = sex.Message;
            }
          }
    
          return (dNum);
        }
    
    0 讨论(0)
提交回复
热议问题