C#的四舍五入【简洁+实例验证版】
C# 中没有四舍五入函数,事实上我知道的程序语言都没有四舍五入函数,因为四舍五入算法不科学,国际通行的是 Banker 舍入法
Banker 's rounding(银行家舍入)算法,即四舍六入五取偶。事实上这也是 IEEE 规定的舍入标准。因此所有符合 IEEE 标准的语言都应该是采用这一算法的
Math.Round 方法默认的也是 Banker 舍入法
在 .NET 2.0 中 Math.Round 方法有几个重载方法
Math.Round(Decimal, MidpointRounding)
Math.Round(Double, MidpointRounding)
Math.Round(Decimal, Int32, MidpointRounding)
Math.Round(Double, Int32, MidpointRounding)
Decimal,Double是要进行四舍五入的小数
Int32是精确度,0~15,将小数值舍入到指定精度。
MidpointRounding 参数,指定当一个值正好处于另两个数中间时如何舍入这个值
该参数是个 MidpointRounding 枚举
AwayFromZero 当一个数字是其他两个数字的中间值时,会将其舍入为两个值中绝对值较小的值。
ToEven 当一个数字是其他两个数字的中间值时,会将其舍入为最接近的偶数。
网上有一堆自己的改造的四舍五入的写法,貌似微软已经有标准的支持了,特验证了下,应该没有问题吧??
Console.WriteLine("3.451: {0}", Math.Round(3.451, 1, MidpointRounding.AwayFromZero)); //Returns 3.5
Console.WriteLine("3.45: {0}", Math.Round(3.45, 1, MidpointRounding.AwayFromZero)); //Returns 3.5.
Console.WriteLine("3.75: {0}", Math.Round(3.75, 1, MidpointRounding.AwayFromZero)); //Returns 3.8
Console.WriteLine("3.46: {0}", Math.Round(3.46, 1, MidpointRounding.AwayFromZero)); //Returns 3.5. 六入
参考文章http://blog.163.com/chenrunfeng@126/blog/static/2420452720088170475045/