C# 使用int.TryParse,Convert.ToInt32,(int)将浮点类型转换整数时的区别
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);
} }
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://images0.cnblogs.com/blog/69929/201408/181050020654199.png)