For this code block:
int num = 5;
int denom = 7;
double d = num / denom;
the value of d
is 0.0
. It can be forced to work by casting:
double d = ((double) num) / denom;
But is there another way to get the correct double
result? I don't like casting primitives, who knows what may happen.
That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:
5 can be expressed exactly as a double.
If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.
Note that casting the result won't do it
Best way to do this is
Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an
int
to adouble
. If you're just not sure of how it works, look it up in the Java Language Specification. Casting anint
todouble
is a widening primitive conversion.You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
Note that casting the result won't do it. Because first division is done as per precedence rule.
I do not think there is any problem with casting as such you are thinking about.
just use this.