Java math FAQ: How do I round a float or double number to an integer in Java?
Solution: Use Math.round()
to round a float
(or double
) to the nearest integer (int
) in Java.
You can see how this works in the examples that follow, where the result is shown in the comment after each line:
package float2int; public class TestClass { public static void main(String[] args) { System.out.println(Math.round(1.9)); // 2 System.out.println(Math.round(2.0)); // 2 System.out.println(Math.round(2.1)); // 2 System.out.println(Math.round(2.4)); // 2 System.out.println(Math.round(2.5)); // 3 System.out.println(Math.round(2.6)); // 3 } }
Cast to an int
Note that as a practical matter you may need to cast the Math.round
result to an int
, like this:
int x = (int) Math.round(2.6);
This is because Math.round
is overloaded, and one version of the method returns an int
, and the other version returns a long
. If the round
method thinks it is receiving a float
, it will return an int
, so this works:
int x = Math.round(2.6f);
But if round
thinks it’s receiving a double
it will return a long
, so casting it to an int
like this is necessary:
int y = (int) Math.round(2.6);
The first of these two examples works because I have explicitly given round
a float
when I wrote 2.6f
.
In summary, if you want to round a float
or double
to an int
in Java, I hope this is helpful.