C#中的Math.Round()并不是使用的"四舍五入"法。实际上是四舍六入五取偶。
对于这个问题我们常见的解决方式是使用MidpointRounding.AwayFromZero,这个枚举来实现。
Eg:
Math.Round(2.5) //result:2
Math.Round(3.5) //result:4
Math.Round(2.5, MidpointRounding.AwayFromZero); // result:3
Math.Round(3.5, MidpointRounding.AwayFromZero); // result:4
可是我在项目中应用时发现,客户端Math.Round()并没有此枚举选项(并不知道什么原因),
这时候只能自己写一个转换方法来实现
public static decimal MathRoundCorrect(decimal d, int place) {
decimal multiplier =Math.Pow(10, place);
if(d < 0)
multiplier *= -1;
return ((decimal)Math.Floor(((double)(d * multiplier) + 0.5))) / multiplier;
}
这里面用到两个函数1,Math.Pow:返回指定数字的指定次幂。
2,Math.Floor:返回一个最接近它的整数,它的值小于或等于这个浮点数。