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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- Correctly parse PDF paragraphs with Python
- Do the Java Integer and Double objects have unnece
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.
Use the
R
format specifier to convert thedouble
to astring
:See The Round-trip ("R") Format Specifier on MSDN.
(emphasis mine)