C#四舍五入用法实例
C#中没有四舍五入函数,程序语言都没有四舍五入函数,因为四舍五入算法不科学,国际通行的是Banker舍入法
Bankersrounding(银行家舍入)算法,即四舍六入五取偶。事实上这也是IEEE规定的舍入标准。因此所有符合IEEE标准的语言都应该是采用这一算法的。
Math.Round方法默认的也是Banker舍入法
在.NET2.0中Math.Round方法有几个重载方法
Math.Round(Decimal,MidpointRounding) Math.Round(Double,MidpointRounding) Math.Round(Decimal,Int32,MidpointRounding) Math.Round(Double,Int32,MidpointRounding)
将小数值舍入到指定精度。MidpointRounding参数,指定当一个值正好处于另两个数中间时如何舍入这个值
该参数是个MidpointRounding枚举
此枚举有两个成员,MSDN中的说明是:
AwayFromZero当一个数字是其他两个数字的中间值时,会将其舍入为两个值中绝对值较小的值。
ToEven当一个数字是其他两个数字的中间值时,会将其舍入为最接近的偶数。
注意!这里关于MidpointRounding.AwayFromZero的说明是错误的!实际舍入为两个值中绝对值较大的值。不过MSDN中的例子是正确的,英文描述原文是itisroundedtowardthenearestnumberthatisawayfromzero.
所以,要实现四舍五入函数,对于正数,可以加一个MidpointRounding.AwayFromZero参数指定当一个数字是其他两个数字的中间值时其舍入为两个值中绝对值较大的值,例:
Math.Round(3.45,2,MidpointRounding.AwayFromZero)
不过对于负数上面的方法就又不对了
因此需要自己写个函数来处理
第一个函数:
doubleRound(doublevalue,intdecimals) { if(value<0) { returnMath.Round(value+5/Math.Pow(10,decimals+1),decimals,MidpointRounding.AwayFromZero); } else { returnMath.Round(value,decimals,MidpointRounding.AwayFromZero); } }
第二个函数:
doubleRound(doubled,inti) { if(d>=0) { d+=5*Math.Pow(10,-(i+1)); } else { d+=-5*Math.Pow(10,-(i+1)); } stringstr=d.ToString(); string[]strs=str.Split('.'); intidot=str.IndexOf('.'); stringprestr=strs[0]; stringpoststr=strs[1]; if(poststr.Length>i) { poststr=str.Substring(idot+1,i); } stringstrd=prestr+"."+poststr; d=Double.Parse(strd); returnd; }
参数:d表示要四舍五入的数;i表示要保留的小数点后为数。
其中第二种方法是正负数都四舍五入,第一种方法是正数四舍五入,负数是五舍六入。
备注:个人认为第一种方法适合处理货币计算,而第二种方法适合数据统计的显示。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。