I was writing this code:
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
The result is 0. Why is this, and how do I solve this problem?
I was writing this code:
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
The result is 0. Why is this, and how do I solve this problem?
Make the 1 a float and float division will be used
Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.
To get the result you are looking for, explicitly tell java that the numbers are doubles like so:
you should use
or
Integer division returns integer.
The conversion in JAVA is quite simple but need some understanding. As explain in the JLS for integer operations:
And an example is always the best way to translate the JLS ;)
A small example using Eclipse to show that even an addition of two
short
s will not be that easy :This will required a casting with a possible loss of precision.
The same is true for the floating point operators
So the promotion is done on the float into double.
And the mix of both integer and floating value result in floating values as said
This is true for binary operators but not for "Assignment Operators" like
+=
A simple working example is enough to prove this
The reason is that there is an implicit cast done here, this will be execute like
(1/3) means Integer division, thats why you can not get decimal value from this division. To solve this problem use:
The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.
Integer division of course returns the true result of division rounded towards zero. The result of
0.333...
is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you
0.333...
.