0

I can't understand the difference between Convert.ToInt32 and Parsing (int) command when i convert a double number to a int number.My example code is here and i have two different answer when i show it.

class Program
{
    static void Main(string[] args)
    {
        double i = 3.897456465;
        int y;
        y = Convert.ToInt32(i);
        Console.WriteLine(y);
        y = (int)i;
        Console.WriteLine(y);
        Console.ReadKey();
    }
}
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
  • So what are the answers you get, and what did the documentation show you when you looked at it? – Jon Skeet Apr 05 '16 at 19:53
  • i get "4" when i use Convert.ToInt32 and "3" when i use parsing. – Kaan Hızarcı Apr 05 '16 at 19:54
  • some reading. doesnt use doubles but gives an explanation of what happens behind the scenes http://stackoverflow.com/questions/199470/whats-the-main-difference-between-int-parse-and-convert-toint32 – Eminem Apr 05 '16 at 19:55

2 Answers2

4

(int) i; is casting not parsing.

Convert.ToInt32(double) would round the number to nearest 32 bit integer. Whereas casting (int) i; would only take the integer part of the double value and assign it to the variable.

Since one does rounding and the other just take the integer value, you see the difference.

Consider the following example:

double d = 1.99d;
int castedValue = (int) d; //1
int convertedValue = Convert.ToInt32(d); //2

In the above code, casting returned 1 since that is the integer part of the double value, whereas the conversion using Convert.ToInt32 rounded the value.

Habib
  • 219,104
  • 29
  • 407
  • 436
2

From the documentation from Convert.ToInt32(double):

Return Value
Type: System.Int32
value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

From the C# 5 specification section 6.2.1, explicit numeric conversions:

For a conversion from float or double to an integral type [...]

  • [...]
  • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.

(Emphasis mine.)

So basically, Convert.ToInt32 rounds up or down to the nearest int. Casting always rounds towards zero.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194