.Net中Math.Round与四舍五入

 有不少人误将Math.Round函数当作四舍五入函数在处理, 结果往往不正确, 实际上Math.Round采用的是国际通行的是 Banker 舍入法.

      Banker's rounding(银行家舍入)算法,即四舍六入五取偶。事实上这也是 IEEE 规定的舍入标准。因此所有符合 IEEE 标准的语言都应该是采用这一算法的. 这个算法可以概括为:“四舍六入五考虑,五后非零就进一,五后皆零看奇偶,五前为偶应舍 去,五前为奇要进一。”
    请看下面的例子:

   Math.Round(3.44, 1); //Returns 3.4.  四舍

   Math.Round(3.451, 1); //Returns 3.5  五后非零就进一
   Math.Round(3.45, 1); //Returns 3.4. 五后皆零看奇偶, 五前为偶应舍 去

   Math.Round(3.75, 1);  //Returns 3.8  五后皆零看奇偶,五前为奇要进一
   Math.Round(3.46, 1); //Returns 3.5. 六入

  如果要实现我们传统的四舍五入的功能,一种比较简单,投机的方法就是在数的后面加上0.0000000001,很小的一个数.因为"五后非零就进一", 所以可以保证5一定进一.

  当然也可以自己写函数, 下面给出一段代码:

public static decimal UNIT = 0.0.1m

static public  decimal  Round(decimal d)

{

    return Round(d,UNIT)

}

static public decimal Round(decimal d,decimal unit)

{

   decimal rm = d % unit;

   decimal result = d-rm;

   if( rm >= unit /2)

  {

      result += unit;

  } 

  return result ;

}

原文地址:https://www.cnblogs.com/hblxwaz/p/1762474.html