C# 使用int.TryParse,Convert.ToInt32,(int)將浮點類型轉換整數時的區別

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   strong   

int.TryParse,Convert.ToInt32,(int)

這幾種類型在將浮點類型轉換整數時是有差別Convert.ToInt32則會進行四捨五入int.TryParse只能轉換整數,即浮點類型全部會返回0(int)不會進行四捨五入,只取整數部分,小數點部分完全捨棄
using  System;
public    class  DoubleToInt
{
      public    static    void  Main()
    {
        Test_DoubleToInt( 0.4 );
         Test_DoubleToInt( 0.5 );
        Console.ReadKey();
    }
      static    void  Test_DoubleToInt( double  _testNumber)
    {
          int  _i= 0 ;
          for ( int  i= 0 ;i< 10 ;i++)
        {
              if (i!= 0 ){
                _testNumber+= 1 ;
            }
            Console.WriteLine( string .Format( "(int){0}={1}" ,_testNumber,( int )(_testNumber)));
            
            Console.WriteLine( string .Format( "Convent.ToInt32({0})={1}" ,_testNumber,Convert.ToInt32(_testNumber)));
             //int.TryParse只有轉換整數類型,其他返回為0
              int .TryParse(_testNumber.ToString(),   out  _i);
            Console.WriteLine( string .Format( "int.TryParse({0})={1}" ,_testNumber,_i));
        }
        Console.WriteLine( string .Empty);
    } }

 

 

 http://www.cnblogs.com/Dely/p/3791951.html

http://stackoverflow.com/questions/11431793/convert-toint32-rounds-to-the-nearest-even-number

http://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-defaul

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.