Difference in values when converting double to integer using cast or convert

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


Share this post   Email it

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2012 Vikram Lakhotia