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

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

解决方案:

" Math.Floor"会向下四舍五入,"
Math.Ceiling"会向上四舍五入,
而" Math.Truncate"会趋于0四舍五入。
因此," Math.Truncate"类似于正数的" Math.Floor",负数的" Math.Ceiling"。

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

一些例子:

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",四舍五入到最接近的整数或者指定的小数位数。

以下图表和表格可能会有所帮助:

-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
日期:2020-03-23 10:24:44 来源:oir作者:oir