c# - C# 如何*确切地*将 double 转换为十进制?

标签 c# floating-point decimal precision

以下 C# 代码打印 0.1 - 为什么?

var s = "0.1";
var dbl = Double.Parse(s);
var dcml = Convert.ToDecimal(dbl);
Console.WriteLine(dcml.ToString());

难道 0.01 不能用二进制表示,因此它应该打印 0.100000001490116 吗?

最佳答案

dbl 的值正好是 0.1000000000000000055511151231257827021181583404541015625。

这是 0.1 到 17 位有效数字。

documentation for Convert.ToDecimal(Double)状态:

The Decimal value returned by this method contains a maximum of 15 significant digits. If the value parameter contains more than 15 significant digits, it is rounded using rounding to nearest.

conversion from Single (aka float)被记录为更早截断:

The Decimal value returned by this method contains a maximum of seven significant digits. If the value parameter contains more than seven significant digits, it is rounded using rounding to nearest.

如果您调用 Convert.ToDecimal(Double) 并使用最初从 0.1f 转换而来的值,它将显示 0.100000001490116:

double dbl = 0.1f;        
decimal dcml = (decimal) dbl;
Console.WriteLine(dcml);

关于c# - C# 如何*确切地*将 double 转换为十进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56190260/

相关文章:

c# - 模仿 File.Move 如果目的地已经存在

c - 超快舍入函数(PBC)

Python小数

c# - 哪些值不能用 double 正确表示

Python: float 到十进制的转换和随后的移位可能会给出错误的结果

C# 扩展 SoapExtension -

c# - 禁用默认按钮或在 asp.net c# 中输入 key

c# - 将子属性绑定(bind)到 DataGridView

math - float 学有问题吗?

c# - 为什么C#的十进制使用二进制整数有效位?