C#双倍到十进制精度损失

编程入门 行业动态 更新时间:2024-10-11 17:24:15
本文介绍了C#双倍到十进制精度损失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个双重138630.78380386264,我想把它转换成十进制,但是当我这样做的时候,我可以通过转换或者使用 Convert.ToDecimal()并且我松动精度。

发生了什么事?十进制和双数都可以保存此号码:

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 不能精确地代表双精度。最接近的双精度数字(如此处所示)为 138630.783803862635977566242218017578125 ,它符合你的发现。

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

此方法返回的十进制值最多包含15位有效数字。如果value参数包含超过15个有效数字,则使用舍入到最近的四舍五入。以下示例说明Convert.ToDecimal(Double)方法如何使用舍入到最接近的方式返回15位有效数字的十进制值。

正如上面显示的那样,双重值,四舍五入到最接近15个有效数字的 138630.783803863 。

I have a double "138630.78380386264" and I want to convert it to a decimal, however when I do so I do it either by casting or by using Convert.ToDecimal() and I loose precision.

What's going on? Both decimal and double can hold this number:

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");

Also: how can I get the ToString() on double to print out the same result as the debugger shows? e.g. 138630.78380386264?

解决方案

138630.78380386264 is not exactly representable to double precision. The closest double precision number (as found here) is 138630.783803862635977566242218017578125, which agrees with your findings.

You ask why the conversion to decimal does not contain more precision. The documentation for Convert.ToDecimal() has the answer:

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.

The double value, rounded to nearest at 15 significant figures is 138630.783803863, exactly as you show above.

更多推荐

C#双倍到十进制精度损失

本文发布于:2023-11-24 19:58:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626611.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:双倍   精度   损失   到十进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!