C# double to decimal 精度损失

标签 c# double decimal precision

我有一个 double "138630.78380386264",我想将它转换为小数,但是当我这样做时,我要么通过强制转换,要么通过使用 Convert.ToDecimal() 我失去了精度。

这是怎么回事? decimal 和 double 都可以保存这个数字:

enter image description here

double doub = double.Parse("138630.78380386264");
decimal dec = decimal.Parse("138630.78380386264");
string decs = dec.ToString("F17");
string doubse =DoubleConverter.ToExactString(doub);
string doubs = doub.ToString("F17");

decimal decC = (decimal) doub;
string doudeccs = decC.ToString("F17");
decimal decConv = Convert.ToDecimal(doub);
string doudecs = decConv.ToString("F17");

另外:我怎样才能使 ToString() 双重打印出与调试器显示相同的结果?例如138630.78380386264?

最佳答案

138630.78380386264 不能精确表示为 double 。最接近的 double (找到 here )是 138630.783803862635977566242218017578125,这与您的发现一致。

您问为什么转换为十进制不包含更高的精度。 documentation for Convert.ToDecimal()有答案:

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. The following example illustrates how the Convert.ToDecimal(Double) method uses rounding to nearest to return a Decimal value with 15 significant digits.

double 值,四舍五入到最接近的 15 位有效数字是 138630.783803863,与上面显示的完全相同。

关于C# double to decimal 精度损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7453900/

相关文章:

java.lang.NumberFormatException : For input string error while converting hex to decimal 异常

c# - 我如何按代码(或任何字段)对项目列表求和?

c# - 根据评级显示项目 MVC

c# - 如何使用 Entity Framework Core 的内存数据库提供程序测试数据库 View ?

c# - session 已关闭对象名称 : 'ISession' . 在 NHibernate.Impl.AbstractSessionImpl.ErrorIfClosed() - 如何阻止 session 过早关闭

c - 需要帮忙进行数组赋值

Android - SharedPreference 转换为 Double

string - Swift – 带逗号分隔符的字符串加倍

html - 浏览器位置 :absolute and decimal truncation?

C# 将字符串转换为 double /十进制并返回字符串,保留尾随零,为千位添加逗号