.NET中Math.Floor()和Math.Truncate()的区别是什么?


当前回答

根据Floor的数学定义,即“小于或等于一个数字的最大整数”,这是完全明确的,而Truncate只是删除小数部分,这相当于四舍五入到0。

其他回答

Math.Floor():返回小于或等于指定的双精度浮点数的最大整数。

round():将值舍入为最接近的整数或指定的小数位数。

Math.Floor()轮 "朝向负无穷"符合IEEE标准754第4节。

Math.Truncate()舍入“最接近零的整数”。

Math.floor()将始终向下舍入。,返回LESSER整数。While round()将返回NEAREST整数

math.floor ()

返回小于或等于指定数字的最大整数。

math.truncate ()

计算一个数的积分部分。

Math.Floor()舍入到负无穷

数学。向上或向下截断舍入到零。

例如:

Math.Floor(-3.4)     = -4
Math.Truncate(-3.4)  = -3

Math.Floor(3.4)     = 3
Math.Truncate(3.4)  = 3

以下是MSDN对以下内容的描述:

Math.Floor, which rounds down towards negative infinity. Math.Ceiling, which rounds up towards positive infinity. Math.Truncate, which rounds up or down towards zero. Math.Round, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)" becoming 3).

下面的图表可能会有所帮助:

-3        -2        -1         0         1         2         3
 +--|------+---------+----|----+--|------+----|----+-------|-+
    a                     b       c           d            e

                       a=-2.7  b=-0.5  c=0.3  d=1.5  e=2.8
                       ======  ======  =====  =====  =====
Floor                    -3      -1      0      1      2
Ceiling                  -2       0      1      2      3
Truncate                 -2       0      0      1      2
Round (ToEven)           -3       0      0      2      3
Round (AwayFromZero)     -3      -1      0      2      3

请注意,Round比它看起来强大得多,因为它可以舍入到特定的小数点后数位。其他的都是0小数。例如:

n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven);       // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15

对于其他函数,你必须使用乘除技巧来达到相同的效果:

c = System.Math.Truncate (n * 100) / 100;                    // 3.14
d = System.Math.Ceiling (n * 100) / 100;                     // 3.15