Java Math round() Method with Examples

Rounding the given number to the nearest integer (Java Math round method)

Now let’s have a look at another method, which is round. As the name says, it rounds the given double or float number to the nearest integer. This method is also overloaded. Let’s have a look at the first variant, which takes double data as input, and returns its nearest integer(long type data). This is just like rounding off.

For example, the number 17.89 rounds off to 18, while the number 17.4 rounds off to 17. Let’s have an example now –

import java.lang.Math;
public class UnderstandingMath {
public static void main(String[] args) {
System.out.println(Math.round(17.89769576467));
}
}

The output of the above program is 18, which is the nearest integer(long type data) to the given number. You can also try putting another value, and take the reference to the below program to understand the behavior of the method.

import java.lang.Math;
public class UnderstandingMath {
public static void main(String[] args) {
System.out.println(Math.round(16.43554126756));
}
}

The output of this program comes out to be 16 since it is the nearest integer to the given double value. Now let’s try to do the same thing with a float value. Remember that when the argument is the float value, the return value is an integer. While if the argument is double, the return type is long.

import java.lang.Math;
public class UnderstandingMath {
public static void main(String[] args) {
System.out.println(Math.round(16.8970f));
}
}

The above program gives output as 17, which is the nearest integer to the given floating-point value. Again, you can try putting some value like 23.2565f, and observe the output. The nearest integer to this number can be found to be 23. So, that should be our output.

Some of the Special cases –

When the argument is double value-

  • If the argument is NaN, the output is 0.

When the argument is a float value –

  • If the argument is NaN, the result is 0.