近日,想把double型变量的小数位缩小点显示,又不想转字符串。
就有了下面的内容:
重载
Round(Decimal, Int32, MidpointRounding) //将小数值舍入到指定数量的小数位,并为中点值使用指定的舍入规则。
Round(Double, Int32, MidpointRounding) //将双精度浮点值舍入到指定数量的小数位,并为中点值使用指定的舍入规则。
Round(Double, MidpointRounding) //将双精度浮点值舍入到最接近的整数,并为中点值使用指定的舍入约定。
Round(Double, Int32) //将双精度浮点值舍入到指定数量的小数位,并将中点值舍入到最接近的偶数。
Round(Double) //将双精度浮点值舍入到最接近的整数值,并将中点值舍入到最接近的偶数。
Round(Decimal, Int32) //将小数值舍入到指定数量的小数位,并将中点值舍入到最接近的偶数。
Round(Decimal) //将小数值舍入到最接近的整数值,并将中点值舍入到最接近的偶数。
Round(Decimal, MidpointRounding) //将小数值舍入到最接近的整数,并为中点值使用指定的舍入规则。
C#中的Math.Round()并不是使用的"四舍五入"法。其实在VB、VBScript、C#、J#、T-SQL中Round函数都是采用Banker’s rounding(银行家算法),即:四舍六入五取偶。事实上这也是IEEE的规范,因此所有符合IEEE标准的语言都应该采用这样的算法。
.NET 2.0 开始,Math.Round 方法提供了一个枚举选项 MidpointRounding.AwayFromZero 可以用来实现传统意义上的"四舍五入"。即:
Math.Round(3.5, MidpointRounding.AwayFromZero) = 4
如:
Math.Round(0.4) //result:0
Math.Round(0.6) //result:1
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
计算出来的小数才是真正的中国式四舍五入!!
下面是微软官方文档:
https://docs.microsoft.com/zh-cn/dotnet/api/system.math.round?view=net-5.0