Converting double to integer using cast and convert statement

Check out the code below.

double d = 13.6;

int i1 = Convert.ToInt32(d);
int i2 = (int)d;

if (i1 == i2)
{ Console.WriteLine("Equal"); }
else
{ Console.WriteLine("Not Equal"); }


The output of the above program would be “Not Equal”.  The reasons being different rounding policy for in convert and cast operator.

In the above program the actual value of i1 is 14 and i2 is 13 convert.ToInt32 uses Math.Round and the direct cast uses Math.floor for rounding values to integer from double.

It's always better to call Math.Ceiling() or Math.Floor() (or Math.Round with MidpointRounding that meets our requirements)

int i1 = Convert.ToInt32( Math.Ceiling(d) );
int i2 = (int) Math.Ceiling(d);

 

Vikram

No Comments