I have a text representation of a double and want to know if it's safe to round-trip it to double and back. How do I know this if I also want to accept any kind of number-style of the input? Or how do I know if any precision is lost when a double-string is parsed with Double.Parse? Or how do I ToString a double to match the same format as another double-string? An answer to any of these questions would be a solution I think.
-
What have you already tried? Some tests maybe? – Sergei Rogovtcev Aug 22 '12 at 09:06
-
What do you mean by "match the same format as another double-string"? Do you have this format specified, or not? I.E. I now hereby provide you this string: "123sd344+334.ere" and I claim it is a well-formatted double number. How do you guess what is the format? – quetzalcoatl Aug 22 '12 at 09:07
-
Hmmmm. I'm thinking of limiting the number of significant digits and exponent to something so I can guarantee than any number written in the format #.#E# is roundtrip-safe. – Andreas Zita Aug 22 '12 at 10:56
3 Answers
Use the R
format specifier to convert the double
to a string
:
myDouble.ToString("R")
See The Round-trip ("R") Format Specifier on MSDN.
The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value. This format is supported only for the Single, Double, and BigInteger types.
(emphasis mine)

- 489,969
- 99
- 883
- 1,009
-
That applies to double -> string -> double, but does not help with string -> double -> string. – JohnB Aug 22 '12 at 09:31
-
@JohnB - It entirely depends on the original representation of the `double` as a string. One has to assume a consistent representation to begin with. – Oded Aug 22 '12 at 09:33
-
2The "R" converter is not reliable. See http://stackoverflow.com/questions/24299692/why-is-a-round-trip-conversion-via-a-string-not-safe-for-a-double?rq=1 for more info. – supercat Jul 05 '14 at 20:05
If has 15 significant digits or less in decimal form, then it's string->double->string round-trip safe.
If it has more digits, then it depends on its value. Maybe convert string->double->string->double and compare the two double values for equality.

- 1,327
- 11
- 33
Of course, this is not round-trip safe for several reasons:
The number format gets lost when parsing a String to a double, since the double does not contain any information about its visual representation.
While the string representation will normally be decimal, double is a binary floating point number. So 0.1 in double will not be exactly 0.1, since the binary representation of 0.1 does not have finitely many digits. You can parse to decimal instead of double in order to avoid this problem.
I would suggest building a struct that stores both the number and the string representation.

- 13,315
- 4
- 38
- 65