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
  • 297,002
  • 52
  • 306
  • 350
The Kanguru
  • 313
  • 1
  • 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
  • 297,002
  • 52
  • 306
  • 350
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
  • 502,043
  • 27
  • 286
  • 360
Eran
  • 387,369
  • 54
  • 702
  • 768
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
  • 850
  • 1
  • 8
  • 24