How to know if a double string is round-trip safe?
Asked Answered
T

3

7

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.

Tauro answered 22/8, 2012 at 9:3 Comment(3)
What have you already tried? Some tests maybe?Anhydrous
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?Molokai
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.Tauro
Y
6

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)

Ynes answered 22/8, 2012 at 9:12 Comment(3)
That applies to double -> string -> double, but does not help with string -> double -> string.Ultraism
@Ultraism - It entirely depends on the original representation of the double as a string. One has to assume a consistent representation to begin with.Ynes
The "R" converter is not reliable. See #24300192 for more info.Coat
P
0

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.

Passel answered 29/4, 2023 at 9:47 Comment(0)
U
-2

Of course, this is not round-trip safe for several reasons:

  1. The number format gets lost when parsing a String to a double, since the double does not contain any information about its visual representation.

  2. 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.

Ultraism answered 22/8, 2012 at 9:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.