#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #991 – Using the Round-Trip Format Specifier

  1. Pingback: Dew Drop – December 9, 2013 (#1679) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: