Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer Conversion in C#

Tags:

c#

int

        string[] strArray = new string[10] { "21.65", "30.90", "20.42", "10.00", "14.87", "72.19", "36.00", "45.11", "18.66", "22.22" };
        float temp = 0.0f;
        Int32 resConvert = 0;
        Int32 resCast = 0;
        for (int i = 0; i < strArray.Length; i++)
        {
            float.TryParse(strArray[i], out temp);
            resConvert = Convert.ToInt32(temp * 100);
            resCast = (Int32)(temp * 100);
            Console.WriteLine("Convert: " + resConvert + " ExplCast: " + resCast);
        }

Ans :

   Convert: 2165 ExplCast: 2164   // ??
   Convert: 3090 ExplCast: 3089   // ??
   Convert: 2042 ExplCast: 2042
   Convert: 1000 ExplCast: 1000
   Convert: 1487 ExplCast: 1486   //??
   Convert: 7219 ExplCast: 7219
   Convert: 3600 ExplCast: 3600
   Convert: 4511 ExplCast: 4511
   Convert: 1866 ExplCast: 1865   //??
   Convert: 2222 ExplCast: 2221   //??

Why the value differs sometimes while doing Explicit Cast , but not always. Any reason ?

like image 927
C-va Avatar asked Jun 29 '12 12:06

C-va


1 Answers

To take one example, 21.65 in float format is actually represented by a number like 21.6499999. The Convert.ToInt32 rounds the number to the nearest integer, yielding 21.65, while the explicit cast (Int32) just truncates (rounding toward zero), so you get 21.64.

If you want the floating point numbers to be represented in the computer the same way they look printed out, use decimal instead of float or double.

like image 160
Gabe Avatar answered Oct 09 '22 12:10

Gabe