Casting a double as an int, does it round or just strip digits?
It does not round, it just returns the integral part before the decimal point.
Reference (thanks Rawling) Explicit Numeric Conversions Table:
When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value.
You can try simple issues like this by yourself by writing simple tests. The following test (using NUnit) will pass and therefore give an answer to your question:
[Test]
public void Cast_float_to_int_will_not_round_but_truncate
{
var x = 3.9f;
Assert.That((int)x == 3); // <-- This will pass
}
Don't be fooled by assuming it rounds down. It strips the decimal off and purely returns the integer portion of the double. This is important with negative numbers because rounding down from 2.75 gives you 2, but rounding down from -2.75 give you -3. Casting does not round down so (int)2.75 gives 2, but (int)-2.75 gives you -2.
double positiveDouble = 2.75;
double negativeDouble = -2.75;
int positiveInteger = (int) positiveDouble;
int negativeInteger = (int) negativeDouble;
Console.WriteLine(positiveInteger + " = (int)" + positiveDouble);
Console.WriteLine(negativeInteger + " = (int)" + negativeDouble);
Console.ReadLine();
//Output: 2 = (int)2.75
// -2 = (int)-2.75
Simply casting just strips everything past the decimal point. To round up or down, you can use the Math.Round() method. This will round up or down and provides a parameter on what to do if its midway. You could also use the Math.Floor() or Math.Ceiling() methods to implicitly round up or round down prior to casting. Here are some examples:
double num1 = 3.5;
double num2 = 3.2;
double num3 = 3.9;
(int)num1 // returns 3;
(int)num2 // returns 3;
(int)num3 // returns 3 also;
(int)Math.Round(num1) // returns 4
(int)Math.Round(num2) // returns 3
(int)Math.Round(num3) // returns 4
(int)Math.Floor(num1) // returns 3
(int)Math.Floor(num2) // returns 3
(int)Math.Floor(num3) // returns 3
(int)Math.Ceiling(num1) // returns 4
(int)Math.Ceiling(num2) // returns 4;
(int)Math.Ceiling(num3) // returns 4;