Convert “1.79769313486232E+308” to double without OverflowException?

后端 未结 8 1329
暗喜
暗喜 2020-12-07 01:20

I have this string \"1.79769313486232E+308\" and am trying to convert it to a .NET numeric value (double?) but am getting the below exception. I am using Convert.ToDo

相关标签:
8条回答
  • 2020-12-07 01:56

    You may try double.Parse() or double.TryParse() rather than Convert.ToDouble(), but I'm not certain you'll get better results. Incidentally, the string that you provide is equal to double.MaxValue, which is (of course) the maximum value that can be contained in a double, so that's likely where your error is coming from. Floating-point numeric types are finicky, so I would assume that some sort of rounding is taking place and pushing it outside the bounds of the type.

    You could also try the decimal data type. You may have better luck there.

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

    Demonstrates the issue and a solution:

    var s = double.MaxValue.ToString();
    double d;
    if (!double.TryParse(s, out d)) {
        d = s.Equals(double.MaxValue) ? double.MaxValue : double.MinValue;
    }
    
    0 讨论(0)
提交回复
热议问题