double.Parse(double.MaxValue.ToString()) yields an Exception

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

"double.Parse(double.MaxValue.ToString())" yields the following Exception:

Value was either too large or too small for a Double.
at System.Number.ParseDouble(String value, NumberStyles options,
NumberFormat
Info numfmt)
at System.Double.Parse(String s, NumberStyles style, NumberFormatInfo info)
at System.Double.Parse(String s)
...

Even double.Parse((double.MaxValue -1).ToString()) states the same error
message.

That's completly illogical. Is this an error or my misunderstanding?
 
Hello,

Problem is caused by rounding in the default implementation of ToString
method. In the example you gave, method creates a string presentation of a
number rounded to a value that is larger than the largest double number
allowed. So, when you try to parse that string, it throws an exception. You
can check this comparing following two outputs:

Console.WriteLine(double.MaxValue.ToString());
Console.WriteLine(double.MaxValue.ToString("E20"));

Therefore this code:

double.Parse(double.MaxValue.ToString("E20"))

will not throw the exception.

Regards,

Julijan
 
Julijan said:
Problem is caused by rounding in the default implementation of ToString
method. In the example you gave, method creates a string presentation of a
number rounded to a value that is larger than the largest double number
allowed. So, when you try to parse that string, it throws an exception. You
can check this comparing following two outputs:

Console.WriteLine(double.MaxValue.ToString());
Console.WriteLine(double.MaxValue.ToString("E20"));

An alternative format specified to use is "R", which is the round-trip
specifier - it always preserves enough information to complete the
format/parse cycle.

Jon
 
Just for completion. The recoverable format is not really recoverable. It
does NOT preseve the milliseconds. You have to serialize the DateTime
(timestamp) as long if you want to preserve them.

Markus
 
Markus Kling said:
Just for completion. The recoverable format is not really recoverable. It
does NOT preseve the milliseconds. You have to serialize the DateTime
(timestamp) as long if you want to preserve them.

The round-trip specifier is a *numeric* specifier. "R" for DateTime
means RFC1123.
 
Back
Top