1

Is it possible to get rid of the "integer division in floating-point context" warning, in this line of code:

int num = 14;
int roundedValue = (Math.round(num / 10) * 10); 
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Which Java compiler is producing this warning? Is it `javac`? An IDE's compiler? Which IDE? – Stephen C Mar 26 '20 at 13:18
  • 1
    It is a Java 11 (Project SDK is set to Java version 11.0.5) project, on Intellij –  Mar 26 '20 at 13:27

2 Answers2

7

Well one solution would be

int roundedValue = (num / 10) * 10; 

Note that integer division truncates, so the Math.round call is superfluous in the above.

On the other hand, this may not give you the answer you are expecting. A possible alternative that gives a different (but maybe more correct) answer is:

int roundedValue = Math.round(num / 10.0) * 10; 

(You will see different results for num = 16, for example.)

In other words, this warning could actually be pointing out a bug in your code! Making warnings "just go away" is a bad idea if the warning is telling you something important.


If you really need to suppress a warning on a specific line with Intellij; see Disable warning in IntelliJ for one line. (Using the IDE shortcut means you don't have to know the compiler specific warning name.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

You could try casting your integer to a floating point:

int num = 14;
int roundedValue = (Math.round(((float) num) / 10) * 10); 
Dashman
  • 1
  • 1