C#中Math.Round()实现中国式四舍五入问题

  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:返回一个最接近它的整数,它的值小于或等于这个浮点数。

 

转载于:https://www.cnblogs.com/bicycleHus/p/5473856.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值