add-semi-colons
add-semi-colons

Reputation: 18800

Divide two floating values give zero

I have been in the python and scala world for sometime so not having reply or interpreter is really giving me nightmares of debugging. I have following code:

int count = someInteger;
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
    if(!entry.getKey().equals("20") && top5 < 5) {
        String movie = entry.getKey();
        int xandy = entry.getValue();
        System.out.println(movie + "," + Float.toString(xandy / count));
        top5 += 1;
    }
}

The issue here is that I get zero from the devision. I thought I have handle the type variables correctly. I have tried the answers provided but still doesn't work but the problem is still getting zero:

Could this be causing the issue:

Note: Recompile with -Xlint:unchecked for details.

Upvotes: 0

Views: 418

Answers (2)

porfiriopartida
porfiriopartida

Reputation: 1556

Try this:

int count = someInteger;
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
    if(!entry.getKey().equals("20") && top5 < 5) {
        String movie = entry.getKey();
        int xandy = entry.getValue();
        System.out.println(movie + "," + Float.toString((float)xandy / (float)count));
        top5 += 1;
    }
}

Note the float cast for xandy and count

Upvotes: 2

rgettman
rgettman

Reputation: 178243

You are performing integer division in Java, which results in an integer, so any decimal part of the division is truncated.

To get the floating-point quotient, first cast one of the variables as a float or a double so floating-point division will occur.

((float) xandy / count)

According to the JLS, Section 15.17.2:

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

Casting one of them to float is enough. Java will promote the other operand to a float to match types, then perform the division.

Upvotes: 1

Related Questions