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

﹥>﹥吖頭↗ 提交于 2019-12-10 16:44:14

问题


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.


回答1:


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)




回答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.



来源:https://stackoverflow.com/questions/12069664/how-to-know-if-a-double-string-is-round-trip-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!