Converting a double to an int in C#

c# convert double to int without rounding
cannot convert double to int c#
convert object to double c#
convert string to int c#
c# convert double to int round up
c# double to int round down
convert decimal to int c#
convert double to long c#

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.

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

Converting a double to an int in C#, C# Cast to Int (Convert Double to Int). Cast ints using the explicit syntax form. See the results of casting to int from different values. Cast, int. Floating point values  C# Program to convert a Double to an Integer Value Csharp Programming Server Side Programming To convert a Double value to an integer value, use the Convert.ToInt32() method. Int32 represents a 32-bit signed integer.

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.

C# Cast to Int (Convert Double to Int), Converts a specified value to a double-precision floating-point number. C# Copy. [System.CLSCompliant(false)] public static double ToDouble (sbyte value); static member ToDouble : sbyte value: SByte. The 8-bit signed integer to convert. The (int) cast in C# programs is useful when converting from a double or other floating point value to an integer, but it never rounds up. This may be acceptable, but may also be problematic. Tip: For more sophisticated rounding, check out the Math.Round method in the System namespace. Math.Round

you can round your double and cast ist:

(int)Math.Round(myDouble);

Convert.ToDouble Method (System), The implicit conversions from int , uint , long , or ulong to float and from long or ulong to double may cause a loss of precision, but never a loss  C# Convert.ToInt32(double) Method Convert.ToInt32(double) Method is used to convert a specific double value (a double precision floating point number) to its equivalent integer (int 32 bytes signed number).

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

Built-in numeric conversions, For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double . Or you might need to  Convert int to double in C#. ConvertDataTypes is the helpfull website for converting your data types in several programming languages.

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

Casting and type conversions, WriteLine(d2); int i1 = Convert. double d = 3.49; int i = Convert.ToInt32(d); Round call (see, for instance "C# Rounding MidpointRounding. Converts the value of the specified object to an double-precision floating-point number, using the specified culture-specific formatting information. ToDouble (UInt64) Converts the value of the specified 64-bit unsigned integer to an equivalent double-precision floating-point number. ToDouble (UInt32) Converts the value of the specified 32-bit

[Solved] conversion of double to int (Rounding), In C#, there are two types of casting: Implicit Casting (automatically) - converting a smaller type to a larger type size char -> int -> long -> float -> double Here you will learn how to convert a numeric string to the integer type. In C#, you can convert a string representation of a number to an integer using the following ways: The Parse () methods are available for all the primitive datatypes. It is the easiest way to convert from string to integer. The Parse methods are available for 16, 32, 64

C# Type Casting, cs(14,21): error CS0266: Cannot implicitly convert type `double' to `int'. An explicit conversion exists (are you missing a cast?) So, if we want to assign a value of  The .NET Framework provides a couple built in ways to convert a C# string to int, or several other numeric datatypes. It is important that you do so in a way that does not throw potential exceptions. Unsafe Ways to Convert a C# String to Int. You can use a couple built in methods, as shown below, to convert a string to int.

C#, We can convert int to double in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly. Java  bool byte byte [] char decimal double float int long sbyte short string uint ulong ushort. Convert int to double in C# double vOut = Convert.ToDouble (vIn); The most viewed convertions in C# Convert int to long in C#79625 hits. Convert int to short in C#53491 hits. Convert int to double in C#53253 hits. Convert string to long in C#50920 hits.

Comments
  • Math.Truncate(score) is more explicitly express intention than (int)score
  • But Math.Truncate returns a double or decimal, not an int
  • Your link actually explains it best, and its not as simple as round vs truncate: 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.
  • @ericosg: Yeah, that would mask the difference if score were 8.5 instead of 8.6. I updated the answer to include the quotes. Thanks for the input.
  • And if score is NaN or an infinity or finite but outside the range of Int32, then Convert.ToInt32 will throw an exception. Cast will return an int, but you won'y know which one (in my implementation it's Int32.MinValue) because you're in unchecked context. (Should you be in checked context, the cast will throw an exception as well in these cases.)
  • @JeppeStigNielsen: Thanks for the input, I updated the answer to mention this too.
  • Nice. But I think the Double type number 10000000000.6 (ten billion point six) is a "real" number. Using a cast to int on that will give a strange result (unless you're in checked context, but you probably aren't).
  • Bonus question - what happens of if the value of the double is too large to push into the int? I.e. if it's higher than int.MAX_VAL?
  • @KonradViltersten Throws an exception Value was either too large or too small for an Int32.
  • the question was now how to make i1 == i2. The question was about why they are not equal. Downvoted.