Saturday, April 22, 2006

C# cast, rounding, conversion


using System;
public class a
{
static void Main()
{
int i;

double d = 3.5;

i = System.Convert.ToInt32(d);

System.Console.WriteLine("Convert: {0}",i); // uses banker's rounding




d = 3.5;

i = (int) d; // doesn't use banker's rounding, result in 4

System.Console.WriteLine("Typecast: {0}",i);


d = 3.5;

i = (int) Math.Round(d,0); // uses banker's rounding

System.Console.WriteLine("Round then typecast: {0}",i);



}
}



output:


Convert: 4
Typecast: 3
Round then typecast: 4

No comments: