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 ;

    }

  • 相关阅读:
    Linux下wget下载软件小技巧以及安装jdk、tomcat与ftp服务器
    C++计算二叉树的节点数和高度
    转:POST 400 Bad Request The request sent by the client was syntactically incorrect
    SSM项目spring配置文件详细步骤(分门别类、灵巧记忆)
    IntelliJ IDEA里找不到javax.servlet的jar包
    51nod 1533 && CF538F
    51nod 1189
    51nod 1225
    51nod 1040
    51nod 1610
  • 原文地址:https://www.cnblogs.com/hblxwaz/p/1762474.html
Copyright © 2011-2022 走看看