Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.ToDouble(). What is the proper way to do this conversion?

OverflowException: Value was either too large or too small for a Double

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
512 views
Welcome To Ask or Share your Answers For Others

1 Answer

Unfortunately this value is greater than double.MaxValue, hence the exception.

As codekaizen suggests, you could hard-code a test for the string. A better (IMO) alternative if you're the one producing the string in the first place is to use the "r" format specifier. Then the string you produce will be "1.7976931348623157E+308" instead, which then parses correctly:

string s = double.MaxValue.ToString("r");
double d = double.Parse(s); // No exception

Obviously that's no help if you don't have control over the data - but then you should understand you're likely to be losing data already in that case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...