I have to divide two integers and get a float as result My Code:
Float ws;
int i = Client.getInstance().getUser().getGespielteSpiele() -Client.getInstance().getUser().getGewonneneSpiele();
int zahl1 = Client.getInstance().getUser().getGewonneneSpiele();
ws = new Float((zahl1 / i));
I check the values with the debugger
i = 64
zahl1 = 22
ws = 0.0
Why is the result of ws 0.0? What I should do to get the correct float?
When you divide two ints you perform integer division, which, in this case will result in 22/64 = 0. Only once this is done are you creating a float. And the float representation of 0 is 0.0. If you want to perform floating point division, you should cast before dividing:
ws = ((float) zahl1) / i;
zahl1 / i is computed as int division and then converted to Float by the Float constructor. For floating point division, cast one of the operands to float or double:
ws = new Float((float)zahl1 / i);
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