为什么 ToString() 对我的 Double 值进行四舍五入?
如何防止双精度值在转换为字符串时被舍入?我尝试了 Convert.ToString
和 ToString()
,结果相同。
例如,我的双精度可能看起来像 77.987654321
,两个字符串转换为 77.98765
。我需要保持原值的精度。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
默认情况下,
Double
的.ToString()
方法返回 15 位精度。如果您想要 double 值在内部保存完整的 17 位数字,则需要将“G17”格式说明符传递给该方法。源自 MSDN 文档:
By default the
.ToString()
method ofDouble
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.Sourced from the MSDN docs:
尝试类似
另请参阅往返(“R”)格式说明符< /a>:
Try something like
See also The Round-trip ("R") Format Specifier:
Jon Skeet 的
DoubleConverter
类有一个ToExactString()
方法,该方法将以字符串形式返回 double 的精确值。https://jonskeet.uk/csharp/DoubleConverter.cs
Jon Skeet's
DoubleConverter
class has aToExactString()
method which will return the exact value of the double as a string.https://jonskeet.uk/csharp/DoubleConverter.cs
我认为四舍五入最后两位数字的主要答案是隐藏由于浮点/双精度有限精度而导致的数值不稳定/四舍五入。
没有四舍五入的示例:
最后 3 位数字看起来有点奇怪,对吧?
四舍五入示例:
看起来“完美”,对吧?
:-)
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:
Looks a bit strange in the last 3 digits, right?
Example with rounding:
Look "perfect", right?
:-)
对于使用 .NET/.NET Core 更新版本的任何人:
.NET Core 3.0 引入了一项重大更改,将
double.ToString()
更改为不再使用"G15"
作为默认格式。相反,ToString()
返回最短的字符串,解析时返回相同的值。因此,为了保持精度,您可以简单地使用
ToString()
。这类似于旧版本的
"R"
格式说明符,但即使如此,在此更改之前显然也不是 100% 准确。请参阅重大事件.NET Core 3.0 中的变化
For anyone using updated versions of .NET/.NET Core:
.NET Core 3.0 introduced a breaking change that changed
double.ToString()
to no longer use"G15"
as the default format. InsteadToString()
returns the shortest string that when parsed returns the same value.Therefore, to maintain precision, you can simply use
ToString()
.This is similar to older versions'
"R"
format specifier, but even that was apparently not 100% accurate prior to this change.See Breaking changes in .NET Core 3.0
没有保证,但请尝试 ToString("R")。
No guarantees, but try ToString("R").