How to use the Java Math.round() method

The Math.round() method in Java is used to round a number to its​ closest integer. This is done by adding 1/21/2 to the number, taking the floor of the result, and casting the result to an integer data type.

svg viewer

Some of the edge cases of the Math.round() method are:

  • If the argument is NaN (not a number), then the function will return 00.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, then the function returns Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, then the function returns Integer.MAX_VALUE.

Let’s see the implementation of the Math.round( ) method:

Basic use

We take a number 74.67 and pass it to the round() function. The output will be a nearest integer 75.

import java.lang.Math; // Needed to use Math.round()
class Program {
public static void main( String args[] ) {
double num1 = 74.65;
System.out.println(Math.round(num1));
}
}

Negative numbers

We pass a negative number -4.3 to the method and it returns -4.

import java.lang.Math; // Needed to use Math.round()
class Program {
public static void main( String args[] ) {
double num1 = -4.3;
System.out.println(Math.round(num1));
}
}

Specific decimal places

If we want to round a decimal number upto specific decimal places, in this case 2 decimal places we multiply it by 100.0 , pass it to the Math.round() method and then multiply it by 100.0 again.

import java.lang.Math; // Needed to use Math.round()
class Program {
public static void main( String args[] ) {
double num1 = -13.56934;
System.out.println(Math.round(num1 * 100.0) / 100.0); // Round to two decimal places
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved