Thursday, May 04, 2006

Floating point number .. an interesting issue

Last night I was doing some work and came across a very interesting situation, I have simulated the problem with a simple example, consider I have written a class which has 3 function with the same name , all of them takes one floating point number as an argument.
class MyClass {
void Display( decimal number ) { Console.WriteLine( "{0} {1}", number.GetType(), number ); }

void Display( float number ) { Console.WriteLine( "{0} {1}", number.GetType(), number ); }
void Display( double number ) { Console.WriteLine( "{0} {1}", number.GetType(), number ); }
static void Main( ) { MyClass m = new MyClass(); m.Display( 1000.90 ); Console.ReadLine(); } }

Here, the question is which "Display" function will be get called ? I have tried out lot of numbers and I have found that every time "Display( double number)" get called.
then I have looked into the IL, it looks like the following line ..
IL_0007: ldc.r8 1000.9IL_0010: callvirt instance float64 QuestionsTest.MyClass::Display(float64)

which means it will call the routine which takes 64 bit float, i.e. double, I was wondering why does it happen .... then I have found something form the MSDN library which says "By default, a real numeric literal on the right-hand side of the assignment operator is treated as double, Therefore, to initialize a float variable, use the suffix f or F, and to initialize a decimal variable use the suffix m or M".

I have modified the main routine in the following manner ....
m.Display( 1000.90 );
m.Display( 1000.90f );
m.Display( 1000.90m );

and I found the following output ..
System.Double 1000.9
System.Single 1000.9
System.Decimal 1000.90

So the conclusion is when we have to write routines with same name and will take floating point number as argument we have to be little cautious when we will call them.
Comments are welcome.

No comments: