Math.Floor()和Math.Truncate()之间的区别

时间:2020-03-05 18:37:13  来源:igfitidea点击:

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

解决方案:

" Math.Floor"会四舍五入," Math.Ceiling"会四舍五入,而" Math.Truncate"会四舍五入。因此," Math.Truncate"类似于正数的" Math.Floor",而类似于负数的" Math.Ceiling"。这是参考。

为了完整起见,Math.Round会四舍五入到最接近的整数。如果数字恰好在两个整数之间,则将其舍入为偶数。参考。

另请参阅:Pax Diablo的答案。强烈推荐!

一些例子:

Round(1.5) = 2
Round(2.5) = 2
Round(1.5, MidpointRounding.AwayFromZero) = 2
Round(2.5, MidpointRounding.AwayFromZero) = 3
Round(1.55, 1) = 1.6
Round(1.65, 1) = 1.6
Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6
Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7

Truncate(2.10) = 2
Truncate(2.00) = 2
Truncate(1.90) = 1
Truncate(1.80) = 1

请通过以下链接获取有关以下内容的MSDN描述:

Math.Floor,向下舍入为负无穷大。 Math.Ceiling,向上取整为正无穷大。 " Math.Truncate",向上或者向下舍入为零。 " Math.Round",四舍五入到最接近的整数或者指定的小数位数。我们可以指定行为是否在两种可能性之间完全等距,例如四舍五入,以使最终数字为偶数(" Round(2.5,MidpointRounding.ToEven)"变为2)或者使其远离零("Round(2.5,MidpointRounding.AwayFromZero)"变为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"比它看起来强大得多,仅仅是因为它可以舍入到特定数量的小数位。其他所有的数字总是四舍五入到零。例如:

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