Related Tags

java
math
round
method

# How to use the Java Math.round() method

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

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

• If the argument is NaN (not a number), then the function will return $0$.
• 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.

## Code

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));

float num2 = 1337.345523f;
System.out.println(Math.round(num2));
}
}

RELATED TAGS

java
math
round
method