0

How to divide two numbers in Java and get to different types in two different situations:

  • Get int if it is possible(for example 6 / 2)
  • Otherwise, get float(6 / 4)

Code like this:

int a;
int b;
float div = a / b;

a and b are integers. (For example, I don`t want to get 2.0 if it is possible to get 2)

  • If you do not know whether the division is "possible" beforehand, then you need a float always. If you do know, then choose among the two ways you have shown beforehand (though you might need to fix the float version...). If that is not the answer you need then you need to clarify your question. – Yunnosch Sep 20 '20 at 09:04
  • Please make a [mre] of the code which might need a float result (and currently uses a float method) but might not need and then can benefit from using an int method. I cannot imagine and think it might be impossible. – Yunnosch Sep 20 '20 at 09:07

2 Answers2

1

You can also just check with the modulo operator if the division is whole - numbered.

int a = 6;
int b = 4;
if(a % b == 0) {
    System.out.print(a/b);
}
else  {
    System.out.print((float)a/b);
}

If the division a % b equals 0 the division is whole numbered. If not then it's a fraction and you can cast just one of the operands(a or b) to a float to get the decimal representing the fraction result.

Output:

1.5
Ritsch1
  • 11
  • 3
0

Try casting the float to an int and compare the results, if it's the same, then print the integer, otherwise, use the float:

public class Main {
    public static void main(String[] args) {
        int a = 6;
        int b = 3;
        getDivisionResult(a, b);
        b = 4;
        getDivisionResult(a, b);
    }
    private static void getDivisionResult(int a, int b) {
        float div = (float) a / b;
        int rounded = (int) div;
        if(rounded == div)
            System.out.println(rounded);
        else
            System.out.println(div);
    }
}

Output:

2
1.5
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • This is vulnerable by the problems described here https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Yunnosch Sep 20 '20 at 12:33