Why is java math.round always rounded?

I have several fields that accept input, a process that happens, and then fields that show output. My problem is that for some reason math.round seems to always be rounded down rather than 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"); } 
+4
source share
1 answer

Your variables are X and Y int , so Java does integer division, here when divided by 6. This is what casts decimal points. It then converts to float before assigning Z By the time he reaches Math.round , the decimal points have already disappeared.

Try distinguishing X from float to force floating point division:

 float Z =((float) X + Y)/6; 

This will save the decimal information that Math.round will use to properly round its input.

An alternative is to specify the float literal for 6 , which will cause the sum of X and Y be different to float before division:

 float Z = (X + Y)/6.0f; 

It cannot be just 6.0 , because this literal is double , and the Java compiler will complain about a "possible loss of precision" when trying to assign double a float .

Here's the corresponding quote from JLS, section 15.17.2 :

Integer divisions are rounded to zero. That is, the factor created for operands n and d, which are integers after binary numeric advancement (ยง5.6.2), is an integer q whose value satisfies the condition | d ยท q | โ‰ค | n |.

+12
source

Source: https://habr.com/ru/post/1483246/


All Articles