Converting a double to an int in C#

Wouter Dorgelo picture Wouter Dorgelo · May 25, 2012 · Viewed 170.1k times · Source

In our code we have a double that we need to convert to an int.

double score = 8.6;
int i1 = Convert.ToInt32(score);
int i2 = (int)score;

Can anyone explain me why i1 != i2?

The result that I get is that: i1 = 9 and i2 = 8.

Answer

Jon picture Jon · May 25, 2012

Because Convert.ToInt32 rounds:

Return 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.

...while the cast truncates:

When you convert from a double or float value to an integral type, the value is truncated.

Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score is a real number as is the case here).