Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is java math.round always rounding down? [duplicate]

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");
}
like image 605
user2201998 Avatar asked May 28 '13 23:05

user2201998


1 Answers

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|.

like image 124
rgettman Avatar answered Oct 04 '22 23:10

rgettman