You need to explicitly get the int value using method intValue() like this:
CopyDouble d = 5.25;
Integer i = d.intValue(); // i becomes 5
Or
Copydouble d = 5.25;
int i = (int) d;
Answer from anubhava on Stack OverflowVideos
You need to explicitly get the int value using method intValue() like this:
CopyDouble d = 5.25;
Integer i = d.intValue(); // i becomes 5
Or
Copydouble d = 5.25;
int i = (int) d;
A Double is not an Integer, so the cast won't work. Note the difference between the Double class and the double primitive. Also note that a Double is a Number, so it has the method intValue, which you can use to get the value as a primitive int.
is there a possibility that casting a double created via
Math.round()will still result in a truncated down number
No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double):
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
For the datatype Double to int, you can use the following:
Double double = 5.00;
int integer = double.intValue();
This truncates (floors), and does not round. Use at your own risk.
You must cast the sum in the numerator of your avg expression to a double or use a double in the denominator:
avg = ((double)(a + b + c) / 3);
or
avg = ((a + b + c) / 3.0);
When you use all ints on the right hand side, the answer is calculated as an int before it is assigned to the double. This is why you are getting a rounded answer.
To fix, one option is to add decimal places to all your denominators like so
avg = ((a + b + c) / 3.0d);
This will force the operation to happen in double
Or you could use the modulo operator:
(d % 1) == 0
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integer type
}
This checks if the rounded-down value of the double is the same as the double.
Your variable could have an int or double value and Math.floor(variable) always has an int value, so if your variable is equal to Math.floor(variable) then it must have an int value.
This also doesn't work if the value of the variable is infinite or negative infinite hence adding 'as long as the variable isn't inifinite' to the condition.