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 ;
}