3

Currently I am working with numbers with high precisions in complex calculations. Some of results and source data should be stored in serialized form. Everything was good till I get magic double value: 0.00000060912702792848.

Writing that value to string (that what XmlWriter does):

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

gives expected result 6.0912702792848E-07.

But magic starts when I try to get double value back (the way how XmlReader works):

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

Converted back value is 0.00000060912702792848005 with 005 extra digits at the end.

It looks like special combination of numbers that gives such result. What do I miss?

Environment: Windows 7 Professional, 64-bit.

Gennadiy
  • 31
  • 1
  • I presume you're aware that floating-point numbers are not meant to be exact? – John Saunders Feb 13 '13 at 10:40
  • Yes, that`s I know. And I whouldn`t wonder if I get a deviation on mathematical operation with doubles. But I am surprised why I get the other number after converting double from string and from where those extra numbers come. – Gennadiy Feb 13 '13 at 12:22

2 Answers2

0

Although not exactly an answer to your question, if you want to get rid of the extra decimals at the end, you may use:

s = d.ToString("G20", NumberFormatInfo.InvariantInfo);
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
  • 1
    I know ways how to hack it. My question was why it happens exactly on that number. And from where those magic digits after converting come. – Gennadiy Feb 13 '13 at 12:26
0

The MSDN documentation for the Roundtrip (R) Format Specifier contains the following note:

In some cases, Double values formatted with the "R" standard numeric format string do not successfully round-trip if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems. To work around this problem, you can format Double values by using the "G17" standard numeric format string. The following example uses the "R" format string with a Double value that does not round-trip successfully, and also uses the "G17" format string to successfully round-trip the original value. (Standard Numeric Format Strings)

I could reproduce your problem when setting the platform to AnyCpu und disabling the prefer 32 bit flag in the project settings. When enabling the prefer 32 bit flag, the parsed double matches the original, serialized value. As the documentation states, you can use the G17 format string to receive the expected values.

Sabacc
  • 789
  • 6
  • 13