Why Is ToString() Rounding My Double Value?

二次信任 提交于 2019-11-27 15:00:44

By default the .ToString() method of Double returns 15 digits of precision. If you want the full 17 digits that the double value holds internally, you need to pass the "G17" format specifier to the method.

String s = value.ToString("G17");

Sourced from the MSDN docs:

By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally. If the value of this instance has greater than 15 digits, ToString returns PositiveInfinitySymbol or NegativeInfinitySymbol instead of the expected number. If you require more precision, specify format with the "G17" format specification, which always returns 17 digits of precision, or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.

Try something like

myDouble.ToString("R")

See also The Round-trip ("R") Format Specifier:

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.

Jon Skeet's DoubleConverter class has a ToExactString() method which will return the exact value of the double as a string.

http://www.yoda.arachsys.com/csharp/DoubleConverter.cs

Bjørn Sigurd Benestad Johansen

I would assume that the main answer for rounding away the last two digits, is to hide numerical instability/rounding due to float/double finite precision.

Example with no rounding:

(Math.Sqrt(7)).ToString("G17") = "2.6457513110645907"

(Math.Sqrt(7)+6).ToString("G17") = "8.6457513110645898"

Looks a bit strange in the last 3 digits, right?

Example with rounding:

(Math.Sqrt(7)).ToString() = "2.64575131106459"

(Math.Sqrt(7)+6).ToString() = "8.64575131106459"

Look "perfect", right?

:-)

No guarantees, but try ToString("R").

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