3

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?

Mureinik
  • 277,661
  • 50
  • 283
  • 320
The Kanguru
  • 313
  • 2
  • 9

4 Answers4

7

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;
Mureinik
  • 277,661
  • 50
  • 283
  • 320
3

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);
Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318
Eran
  • 374,785
  • 51
  • 663
  • 734
3

It's because you're doing integer division,you need to change the int value as float at first.

float ws = (float) zahl1 / i;
2

try:

float ws = (float)zahl1/i;
Stugal
  • 841
  • 1
  • 7
  • 23