Apr 262017
 

If you try converting double.MinValue to string and then back again, you will be greeted with OverflowException:

var text = double.MinValue.ToString(CultureInfo.InvariantCulture);
Console.WriteLine(text);
var number = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
Console.WriteLine(number);

Seemingly output string of -1.79769313486232E+308 is a bit lower than double would go despite the implicit promise minimum value makes: to be a minimum.

Reason for this is ToString() method not showing all the digits it can by default but actually a few less with a bit of rounding. This actually generally gives a better result (for example try 1.0/3). Last digit or two are noise anyhow due to the nature of double.

However, if we are emotionally connected to every possible digit or we need to parse stuff we give as output, there is a little thing called round-trip formatting. That works for Single, Double, and BigInteger data types and it consists of a single “r”:

var text = double.MinValue.ToString("r", CultureInfo.InvariantCulture);
Console.WriteLine(text);
var number = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
Console.WriteLine(number);

Now we get -1.7976931348623157E+308 as a text representation and parsing fails no more.

PS: Equivalent “issue” exists for .MaxValue.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>