#991 – Using the Round-Trip Format Specifier

Normally, when converting a floating point value to a string, you can lose some precision.  If you then later need to convert from the string back to the original floating point data type, you could end up with a different value.  In the example below, we convert from a double to a string and then back again.  But the double that we get in the end is not equal to the original value.

            double d1 = 0.123456789123456789;
            string s1 = d1.ToString();
            double d1b = double.Parse(s1);
            bool b1 = (d1 == d1b);

991-001
You can use the “R” format specifier when converting to a string to indicate that you want to be able to convert back to a floating point value without loss of precision.

            double d1 = 0.123456789123456789;
            string s1 = d1.ToString("R");
            double d1b = double.Parse(s1);
            bool b1 = (d1 == d1b);

991-002

Advertisement