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

后端 未结 8 1335
暗喜
暗喜 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:42

    The problem is likely due to the fact that Double.MaxValue was converted to a string, and when the string is output, not all the digits are output, instead it is rounded. Parsing this value overflows the double.

    Using Double.TryParse and subsequently checking equality on the string "1.79769313486232E+308" in case of failure and substituting Double.MaxValue should be a quick workaround, if you need to keep the string the way it is.

    EDIT: Of course, if you don't need to keep the string the way it is, use the Round Trip format specifier to produce the string in the first place, as Jon describes in his answer.

提交回复
热议问题