以下 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/