How to divide two numbers in Java and get to different types in two different situations:
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)
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.