Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
math
round
method

How to use the Java Math.round() method

Educative Answers Team

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.

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
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring