Math.Round 不同的四舍五入

Math.Round有好多个重载,如下:

[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Round(double a); 

public static double Round(double value, int digits)
{
     if ((digits < 0) || (digits > maxRoundingDigits)) 
         throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
     return InternalRound(value, digits, MidpointRounding.ToEven); 
} 

public static double Round(double value, MidpointRounding mode) { 
   return Round(value, 0, mode);
}

public static double Round(double value, int digits, MidpointRounding mode) { 
    if ((digits < 0) || (digits > maxRoundingDigits))
        throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); 
    if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { 
        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, "MidpointRounding"), "mode");
    } 
    return InternalRound(value, digits, mode);
}

public static Decimal Round(Decimal d) { 
  return Decimal.Round(d,0);
} 
 
public static Decimal Round(Decimal d, int decimals) {
  return Decimal.Round(d,decimals); 
}

public static Decimal Round(Decimal d, MidpointRounding mode) {
  return Decimal.Round(d, 0, mode); 
}
 
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) { 
  return Decimal.Round(d, decimals, mode);
} 

由于翻了源代码,就直接贴了源代码。

这里是有两个版本的,double和decimal版本的,注意这两个版本的代码最终调用的方法可是不一样的哦,后面的现象原因就出在这里

 

先来简单的例子:

Math.Round(12.5)
返回的是12,这个在搜索出来的资料是没有问题,可以解释为Banker 's  rounding(银行家舍入)算法,即四舍六入五取偶,是IEEE规定的舍入标准。

当然我们需要四舍五入的话,需要设置 MidpointRounding .

Math.Round(12.5, MidpointRounding.AwayFromZero)

则返回13。

来看一下MidpointRounding的枚举介绍(MSDN)。

ToEven
当一个数字是其他两个数字的中间值时,会将其舍入为最接近的偶数。

AwayFromZero
当一个数字是其他两个数字的中间值时,会将其舍入为两个值中绝对值较小的值。

在默认情况下都是使用ToEven,在上面的代码中可以发现。

所以一开始以为只要使用AwayFromZero就可以完成四舍五入了。

 

下面再来一个例子:

Math.Round(0.145, 2, MidpointRounding.AwayFromZero)
Math.Round(0.145, 2, MidpointRounding.ToEven)

我想很多同学都会觉得第一个返回0.15,第二个返回0.14.

问题来了,结果不是这样的哦。正确结果两个都是0.14。 哇靠,AwayFromZero没起作用,没给我四舍五入!

不知道还有没有其他存在这样的例子,看样子AwayFromZero也不可靠啊。

其实这里是调用double的方法。

下面来试一下decimal的方法:

Math.Round((decimal)0.145, 2, MidpointRounding.AwayFromZero)
Math.Round((decimal)0.145, 2, MidpointRounding.ToEven)

这回结果与上面的版本不一样哦,得到了我想要的0.15和0.14。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值