Math.Round函數說明__函數

來源:互聯網
上載者:User

經過測試發現Math.Round函數存在這個問題,採用的是“四捨六入五成雙”的方式
     具體參考:http://blog.joycode.com/ghj/posts/9474.aspx
    譬如:Math.Round(1.5) = 2
          Math.Round(2.5) = 2
 
     而Sqlserver中採用的是傳統的四捨五入的方式,為了保證前景程式與後台資料庫的計算方法一致。
     所以在Public中增加了一個類和兩個靜態方法
     可以採用:MyMath.Round()方法來替代Math.Round()的方法

public static decimal Round(decimal number)
  {
      return EMSMath.Round(number,0) ;
  }

  public static decimal Round(decimal number, int dec)
  {
      string numStr = number.ToString() ;

      if(numStr == "0") return (decimal)0.0 ;

      int    decIndex = numStr.IndexOf(".",0) ;

      if(numStr.Length <= decIndex + dec + 1)
          return number ;

      string decStr = numStr.Substring(decIndex + dec + 1) ;

      decStr = decStr.Replace("0","") ;

     if(decStr == "5")
     {
          int lastNum ;

          if(dec == 0)
                lastNum = int.Parse(numStr.Substring(decIndex - 1,1)) ;
         else
               lastNum = int.Parse(numStr.Substring(decIndex + dec,1)) ;

         if( lastNum % 2 == 0)
          {
              decimal addNumer = (decimal)1.0;
              for(int i = 0; i < dec ; i ++)
             {
                 addNumer = addNumer * (decimal)0.1 ;
             }

             return Math.Round(number,dec) + addNumer ;
         }
         else
           return Math.Round(number,dec) ;
       }  
      else
         return Math.Round(number,dec) ;
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.