Parsing C # double value

I am currently working with highly demanding numbers in complex calculations. Some results and source data must be stored in serialized form. Everything was fine until I got a double magic value : 0.00000060912702792848 .

Writing this value to a string (which is what the XmlWriter does):

s = d.ToString("R", NumberFormatInfo.InvariantInfo);

      

gives the expected result 6.0912702792848E-07 .

But the magic starts when I try to return a double value (the way the XmlReader works):

d=double.Parse(s, NumberStyles.Float,  NumberFormatInfo.InvariantInfo);

      

The inverse reciprocal is 0.00000060912702792848005 with additional digits 005 .

It looks like a special combination of numbers that gives this result. What am I missing?

Environment: Windows 7 Professional 64-bit.

+3


source to share


2 answers


While you can't answer your own question, if you want to get rid of the extra decimal places at the end, you can use:



s = d.ToString("G20", NumberFormatInfo.InvariantInfo);

      

0


source


The MSDN documentation for the Roundtrip (R) format specifier contains the following note:

In some cases, double values ​​formatted with the standard "R" number, the formatted string fails backwards if compiled using / platform: x64 or / platform: anycpu toggle and run on 64-bit systems. To work around this problem, you can format double values ​​using the "G17" standard number format string. The following example uses the "R" format string with a double value, which does not round off successfully, and also successfully uses the "G17" format string back to the original value. ( Standard number format strings )



I could reproduce your problem when setting the platform to AnyCpu and disabling the flag prefer 32 bit

in the project settings. When enabled, the prefer 32 bit

parsed double match is the original serialized value. As stated in the documentation, you can use the G17 format string to get the expected values.

0


source







All Articles