Difference in values when converting double to integer using cast or convert
Posted on 8/11/2010 10:57:22 AM
in #Dot Net Framework
Check out the code below./o:p>/SPAN>/P>
double d = 13.6;
/SPAN>int i1 = Convert.ToInt32(d); int i2 = (int)d;/o:p>/P>
if (i1 == i2) { Console.WriteLine("Equal"); } else { Console.WriteLine("Not Equal"); }/o:p>/P>
The output of the above program would be “Not Equal”. /SPAN>The reasons being different rounding policy for in convert and cast operator./o:p>/P>
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./o:p>/P>
It's always better to call Math.Ceiling() or Math.Floor() (or Math.Round with MidpointRounding that meets our requirements)/o:p>/P>
int i1 = Convert.ToInt32( Math.Ceiling(d) ); int i2 = (int) Math.Ceiling(d);/o:p>/P>
/o:p>/P>
Vikram/o:p>/P>
|