Converting a double to an int in C#

C#IntDouble

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Casting will ignore anything after the decimal point, so 8.6 becomes 8.

Convert.ToInt32(8.6) is the safe way to ensure your double gets rounded to the nearest integer, in this case 9.

Solution 3 - C#

you can round your double and cast ist:

(int)Math.Round(myDouble);

Solution 4 - C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

Solution 5 - C#

ToInt32 rounds. Casting to int just throws away the non-integer component.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWouter DorgeloView Question on Stackoverflow
Solution 1 - C#JonView Answer on Stackoverflow
Solution 2 - C#neilgmacyView Answer on Stackoverflow
Solution 3 - C#DavidView Answer on Stackoverflow
Solution 4 - C#Evdzhan MustafaView Answer on Stackoverflow
Solution 5 - C#user146043View Answer on Stackoverflow