Why does the result of 1/3
in Java division equal 0?
I wrote the following code:
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
The result is 0, but I expected a non-zero value. Why is this happening, and how can I fix this issue in Java division to get the correct result?
Classic integer division in Java! The issue here is that both 1
and 3
are integers, so Java performs integer division, which discards the decimal part and gives you 0
. Since 0
is then assigned to g
, it remains 0.00
when printed.
The fix? Use floating-point division by making at least one operand a double:
public static void main(String[] args) {
double g = 1.0 / 3; // Ensure at least one operand is a double
System.out.printf("%.2f", g); // Output: 0.33
}
Now, since 1.0
is a double, Java treats the entire expression as a floating-point operation and gives the expected result!
Yep, integer division strikes again! And while Miro’s solution is spot on, if you want to be extra explicit and ensure precision every time, you can cast the operands to double:
public static void main(String[] args) {
double g = (double) 1 / (double) 3; // Explicitly cast both operands
System.out.printf("%.2f", g); // Output: 0.33
}
This guarantees that java division always happens in floating-point mode. While casting both operands isn’t strictly necessary (since just one would work), it makes the intent clearer in complex expressions.
Exactly, floating-point division is the way to go! But if you need even more control over precision, you might want to round the result to avoid floating-point inaccuracies in certain cases. Java’s Math.round()
can help:
public static void main(String[] args) {
double g = Math.round((1.0 / 3) * 100.0) / 100.0; // Rounds to two decimal places
System.out.printf("%.2f", g); // Output: 0.33
}
This ensures your result is rounded properly to two decimal places. Not always needed, but useful if you’re dealing with precise financial calculations or need to avoid floating-point quirks in java division.