C#中Math.Round()实现中国式四舍五⼊
C#中Math.Round()实现中国式四舍五⼊
C#中的Math.Round()并不是使⽤的"四舍五⼊"法。其实在VB、VBScript、C#、J#、T-SQL中Round函数都是采⽤Banker's rounding(银⾏家算法),即:四舍六⼊五取偶。事实上这也是IEEE的规范,因此所有符合IEEE标准的语⾔都应该采⽤这样的算法。
.NET 2.0 开始,Math.Round ⽅法提供了⼀个枚举选项 MidpointRounding.AwayFromZero 可以⽤来实现传统意义上的"四舍五⼊"。
即: Math.Round(4.5, MidpointRounding.AwayFromZero) = 5。
Round(Decimal)
Round(Double)
Round(Decimal, Int32)
Round(Decimal, MidpointRounding)
Round(Double, Int32)
Round(Double, MidpointRounding)
Round(Decimal, Int32, MidpointRounding)
Round(Double, Int32, MidpointRounding)
如:
Math.Round(0.4) //result:0
Math.Round(0.6) //result:1sql中round函数怎么使用
Math.Round(0.5) //result:0
Math.Round(1.5) //result:2
Math.Round(2.5) //result:2
Math.Round(3.5) //result:4
Math.Round(4.5) //result:4
Math.Round(5.5) //result:6
Math.Round(6.5) //result:6
Math.Round(7.5) //result:8
Math.Round(8.5) //result:8
Math.Round(9.5) //result:10
使⽤MidpointRounding.AwayFromZero重载后对⽐:
Math.Round(0.4, MidpointRounding.AwayFromZero); // result:0
Math.Round(0.6, MidpointRounding.AwayFromZero); // result:1
Math.Round(0.5, MidpointRounding.AwayFromZero); // result:1
Math.Round(1.5, MidpointRounding.AwayFromZero); // result:2
Math.Round(2.5, MidpointRounding.AwayFromZero); // result:3
Math.Round(3.5, MidpointRounding.AwayFromZero); // result:4
Math.Round(4.5, MidpointRounding.AwayFromZero); // result:5
Math.Round(5.5, MidpointRounding.AwayFromZero); // result:6
Math.Round(6.5, MidpointRounding.AwayFromZero); // result:7
Math.Round(7.5, MidpointRounding.AwayFromZero); // result:8
Math.Round(8.5, MidpointRounding.AwayFromZero); // result:9
Math.Round(9.5, MidpointRounding.AwayFromZero); // result:10
但是悲剧的是,如果⽤这个计算⼩数的话,就不灵了!!!
必须⽤第七个重载⽅法,
decimal Round(decimal d, int decimals, MidpointRounding mode)这样计算出来的⼩数才是真正的中国式四舍五⼊!!
?Math.Round(526.925, 2)
526.92
?Math.Round(526.925, 2,MidpointRounding.AwayFromZero)
526.92
?Math.Round((decimal)526.925, 2)
526.92
?Math.Round((decimal)526.925, 2,MidpointRounding.AwayFromZero)
526.93
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论