zoukankan      html  css  js  c++  java
  • .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 ;
    }
  • 相关阅读:
    call 与 apply
    react-router
    阻止IOS上的弹性滚动
    React规范
    sessionStorage 、localStorage 和 cookie 对比区分
    显式Intent 和隐式 Intent 的区别
    Activity之间传递数据的方式及常见问题总结
    Android横竖屏切换生命周期变化
    String、StringBuilder、StringBuffer 区别
    内存泄漏
  • 原文地址:https://www.cnblogs.com/tonykan/p/3793836.html
Copyright © 2011-2022 走看看