小数的取舍

1. Math.Floor & Math.Ceiling(Floor——出头舍;Ceiling——出头算)
 
Math.Floor:
返回小于或等于指定小数的最大整数值。
 
Math.Floor(3.21);//3
Math.Floor(5.952);//5
Math.Floor(0.64);//0
Math.Floor(-0.64);//-1
Math.Floor(-5.2);//-6
Math.Floor(-5.8);//-6
 
Math.Ceiling:
返回大于或等于指定小数的最小整数值。
 
Math.Ceiling(3.21);//4
Math.Ceiling(5.952);//6
Math.Ceiling(0.64);//1
Math.Ceiling(-0.64);//0
Math.Ceiling(-5.2);//-5
Math.Ceiling(-5.8);//-5
 
注意:
返回类型为Double或者Decimal。
 
 
2. Math.Truncate 取整/截断
 
作用:
计算指定小数的整数部分。
 
示例:
Math.Truncate(3.21);//3
Math.Truncate(5.952);//5
Math.Truncate(0.64);//0
Math.Truncate(-0.64);//0
Math.Truncate(-5.2);//-5
Math.Truncate(-5.8);//-5
 
注意:
返回类型为Double或者Decimal。
 
 
3. Math.Round 舍入
 
作用:
Math.Round采取的舍入方式和Convert.ToInt32(Double)一样,都是使用bankers' rounding 规则(四舍六入五成双)
 
示例:
Math.Round(3.21);//3
Math.Round(5.5);//6
Math.Round(4.5);//4
Math.Round(-0.64);//-1
Math.Round(-5.5);//-6
Math.Round(-4.5);//-4
 
小数取舍:
Math.Round(Double, Int32),其中Int32指定返回值的小数位数。
 
示例:
Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.

Math.Round(4.34, 1); // Returns 4.3
Math.Round(4.35, 1); // Returns 4.4
Math.Round(4.36, 1); // Returns 4.4
 
Pasted from <http://msdn.microsoft.com/zh-cn/library/zy06z30k.aspx>
 
 
扩展:
函数默认是按照bankers' rounding 规则(四舍六入五成双)的方法进行舍入。为了可以更灵活的进行舍入,函数添加了System.MidpointRounding 参数。
 
MidpointRounding.AwayFromZero:在正数情况下,这是最常见的四舍五入。在负数情况下,-4.5 -> -5。(负数情况下,-4.5四舍五入是-4还是-5,每个人都见解都不同)。
 
MidpointRounding.ToEven:就是默认的四舍六入五成双。

转自 http://blog.sina.com.cn/s/blog_6d5a77ce0100xpcb.html

原文地址:https://www.cnblogs.com/miaoying/p/5559145.html