Carlos Landeras
Carlos Landeras

Reputation: 11063

Casting double to int different result using (int) and Convert.ToInt(32)

If I am not wrong, when you use

(int)

it is the same than casting to Int32

Convert.ToInt32(value)

I was running a method with the following code:

 public int CurrentAge()
 {
      // return Convert.ToInt32((DateTime.Now - BirthDay).TotalDays)/365;
      return (int)((DateTime.Now - BirthDay).TotalDays)/365;
 }

Using this date:

  DateTime.ParseExact("13-07-1985", "dd-MM-yyyy",null)

And uncommenting the first line, the output is 30, but casting with (int) results in 29. Why is this behaviour?

Reading this post for example:

difference between Convert.ToInt32 and (int)

I understand it should be the same.

Upvotes: 1

Views: 173

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You see the difference because the actual number is 29.5 or above. Casting truncates the value, while Convert performs rounding:

double x = 29.5;
Console.WriteLine("Cast: {0} Convert: {1}", (int)x, Convert.ToInt32(x));

This prints

Cast: 29 Convert: 30

Demo.

Upvotes: 5

John McElreavey
John McElreavey

Reputation: 307

Looks like it has something to do with when you use to Convert.toInt32 you include the /365 but in the other one you don't.

Upvotes: 1

Related Questions