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 ;
    }
  • 相关阅读:
    微信小程序---app.json中设置背景色不生效解决办法
    给网站设置ICO图标
    ajax事件(五)
    ajax关于主流中的异类:应对Opera(四)
    dashboard
    tomcat 清理日志
    jQuery datatable
    php wampserver 80 端口无法开启的解决方法
    mysql 行列转换
    jQuery-2.1.4.min.js:4 Uncaught TypeError: Illegal invocation
  • 原文地址:https://www.cnblogs.com/tonykan/p/3793836.html
Copyright © 2011-2022 走看看