Doing some calculations with doubles which then need to be cast to an int. So i have a quick question, when casting a double say 7.5 to an int, it will return 7.
Is this a product of rounding or just striping anything after the decimal point?
If it is a product of rounding, is it smart ie 0.1 to 0.5 it rounds down and 0.6 to 0.9 it rounds up?
Cheers
However, INT actually is more sophisticated than that. INT rounds a number down using the Order rounding method. That is, it rounds a positive number down, towards zero, and a negative number down, away from zero. Therefore, it's easy to use INT to round a number up using the Math method.
double to int - Math. It accepts a double value and converts into the nearest long value by adding 0.5 and truncating decimal points. Once you got the long value, you can cast it to int again, as shown below: int a = (int) Math.
round() Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.
In case of casting a float / double value to int , you generally loose the fractional part due to integer truncation.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With