Multiplying by an Integer by a Float/Double in Java
I'm Trying to Do Something So Simple: Multiply an Integer by a Float/Double: Public Class a { Public Static Void Main(String[] Args) { Int X = (Int) 0.5 * 100...
I'm trying to do something so simple: multiply an integer by a float/double:
public class A {
public static void main(String[] args) {
int x = (int) 0.5 * 100;
System.out.println(x);
}
}
However, although you'd expect this to return x = 50, instead x = 0! The same thing happens when I use float d = 0.5f. Does anyone know what is going on and why this isn't working?
2 Answers
JLS §4.2.4. Floating-Point Operations tell rules governing floating point operation, so as per that if any of the operand is a floating point number than other operand will be widened to a floating point (if not already) and final result will be a floating point number.
So, your int 100 will be widened to 100.0 before arithmetic operation, and your result of operation will be 50.0.
Now, since you are casting your result to in int, so JSL §5.1.3. Narrowing Primitive Conversion will be applicable, and double 50.0 will be narrowed to int 50.
100 is an impossible result, given the code you have provided.
My guess is that when you got 100, you would have done something else.
int x = (int) 0.5 * 100;
it first casts 0.5 to an int ---> 0 then multiplies.