Doubles, strings and parsing.

A guy at a client site quizzed me the other day on an interesting topic.  Given the following snippet of code:

double value1 = ... ;
string s = value1.ToString();
double value2 = double.Parse(s);

Assume 'value1' is just some random value.  Will 'value1' and 'value2' always be the same?

The answer is No.  With the parameterless ToString(), .NET will use the "G" (General) Numeric Format String.  If you want to guarantee a round-trip conversion from double-to-string and back to double will maintain the same value, use the "R" (Round-trip) specifier when you ToString() the double.

double value1 = ... ;
string s = value1.ToString("R");
double value2 = double.Parse(s);

No Comments