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;
计算机中round函数怎么用}
return result ;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。