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

    }

  • 相关阅读:
    BIOS/MBR UEFI/GPT关系与区别-资料整理
    raid 简单了解
    MBR主引导记录
    linux 安装vscode
    chrome 获得点击按钮时的事件
    python计算纪念日相关
    python error: curl: (1) Protocol "'https" not supported or disabled in libcurl
    linux go with vscode
    postman 进阶技巧
    mysql常用时间函数与类型转换
  • 原文地址:https://www.cnblogs.com/taomylife/p/3488489.html
Copyright © 2020-2023  润新知