Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

c# - Convert "1.79769313486232E+308" to double without OverflowException?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...