使用此双精度值四舍五入到特定位数失败 [英] Rounding to specfic digits fails with this double-precision value

查看:83
本文介绍了使用此双精度值四舍五入到特定位数失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试截断C#中的一系列双精度值.无论我使用哪种舍入方法,以下值都会失败.导致这两种方法均失败的该值有什么问题?为什么连Math.Round都不能正确截断数字?可以使用什么方法来正确截断这些值?

I'm attempting to truncate a series of double-precision values in C#. The following value fails no matter what rounding method I use. What is wrong with this value that causes both of these methods to fail? Why does even Math.Round fail to correctly truncate the number? What method can be used instead to correctly truncate such values?

值:

double value = 0.61740451388888251;

方法1:

return Math.Round(value, digits);

方法2:

double multiplier = Math.Pow(10, decimals)
return Math.Round(value * multiplier) / multiplier;

即使在VS监视窗口中也失败!

Fails even in VS watch window!

推荐答案

Double是浮点型 binary 点类型.它们以二进制系统表示(如11010.00110).当十进制表示双精度数时,这只是一个近似值,因为并非所有二进制数字都以十进制表示精确.例如,尝试以下操作:

Double is a floating binary point type. They are represented in binary system (like 11010.00110). When double is presented in decimal system it is only an approximation as not all binary numbers have exact representation in decimal system. Try for example this operation:

double d = 3.65d + 0.05d;

它不会导致3.7,但会导致3.6999999999999997.这是因为变量包含最接近的double.

It will not result in 3.7 but in 3.6999999999999997. It is because the variable contains a closest available double.

您的情况也是如此.您的变量包含最接近的double.

The same happens in your case. Your variable contains closest available double.

对于精确操作,double/float不是最幸运的选择. 当您需要快速的性能或要在更大范围的数字上进行操作(但不需要高精度)时,请使用double/float.例如,它是用于物理计算的理想类型. 对于精确的十进制运算,请使用decimal.

For precise operations double/float is not the most fortunate choice. Use double/float when you need fast performance or you want to operate on larger range of numbers, but where high precision is not required. For instance, it is perfect type for calculations in physics. For precise decimal operations use, well, decimal.

此处是有关float/decimal的文章: http://csharpindepth.com /Articles/General/FloatingPoint.aspx

Here is an article about float/decimal: http://csharpindepth.com/Articles/General/FloatingPoint.aspx

这篇关于使用此双精度值四舍五入到特定位数失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆