为什么的ToString()舍我的双重价值?我的、价值、ToString

2023-09-03 06:10:24 作者:晚街听风

我如何转换为字符串时,prevent被四舍五入我的双重价值?我曾经尝试都 Convert.ToString 的ToString()具有相同的结果。

How do I prevent my double value from being rounded when converting to a string? I have tried both Convert.ToString and ToString() with the same result.

例如我的双重可能看起来像 77.987654321 ,和两个字符串转换转换为以 77.98765 。我需要保持价值precision原样。

For example my double may look something like 77.987654321, and the two strings conversions convert to to 77.98765. I need to keep the precision of the value as is.

推荐答案

在默认情况下双的的ToString()方法返回1​​5 precision数字。如果你想完整的17位,双值的内部保存,你需要在G17格式说明传递给方法。

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");

从来源MSDN文档:

在默认情况下,返回值   包含15 precision位   虽然最大的17位是   内部维护。如果值   这种情况下具有大于15   数字,toString返回   PositiveInfinitySymbol或   而不是NegativeInfinitySymbol的   预计数。如果你需要更多的   precision,指定格式的   G17的格式规范,   总是返回17 precision数字,   或R,它返回15位数字,如果   号码可以是psented与重新$ P $   precision或17位数字,如果数字   只能重新presented具有最大   precision。

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.

 
精彩推荐