我有一个 double "138630.78380386264"
,我想将它转换为小数,但是当我这样做时,我要么通过强制转换,要么通过使用 Convert.ToDecimal()
我失去了精度。
这是怎么回事? decimal 和 double 都可以保存这个数字:
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/