Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer division to float result [duplicate]

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?

like image 986
The Kanguru Avatar asked Aug 22 '26 21:08

The Kanguru


2 Answers

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;
like image 89
Mureinik Avatar answered Aug 25 '26 10:08

Mureinik


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);
like image 27
Eran Avatar answered Aug 25 '26 11:08

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!