I have a number of fields which take inputs, a process which happens and then fields that show the output. My issue is that for some reason math.round seems to be always rounding down instead of to the nearest integer.
Here is an example
private void method(){
int X= Integer.parseInt(XjTF.getText());
int Y= Integer.parseInt(YjTF.getText());
float Z =(X+Y)/6;
int output = Math.round(Z);
OutputjTF.setText(Integer.toString(output)+" =answer rounded to closest integer");
}
Your X
and Y
variables are int
, so Java performs integer division, here when dividing by 6. That is what is dropping the decimal points. Then it's converted to a float
before being assigned to Z
. By the time it gets to Math.round
, the decimal points are already gone.
Try casting X
to float
to force floating point division:
float Z =((float) X + Y)/6;
That will retain the decimal information that Math.round
will use to properly round its input.
An alternative is to specify a float
literal for 6
, which will force the sum of X
and Y
to be cast to float
before the division:
float Z = (X + Y)/6.0f;
It can't just be 6.0
, because that's a double
literal, and the Java compiler will complain about "possible loss of precision" when attempting to assign a double
to a float
.
Here's the relevant quote from 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|.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With