Java Math round() Method

java math round() method

Java Math Class

Here, in the page we will discuss about the math round() Method in java.
Java Math class provides several methods to perform several operations on math calculations like max(), min(), sin(), cos(), round(), ceil(), floor(), abs() etc.The java.lang.Math class contains various methods for performing basic numeric operations

Java Math round() Method :

The round() built-in math function returns the longest value that is most closely related to the argument.By adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long, the result is rounded to an integer.

Special Points :

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.

Syntax  :

public static long round(double a))

Example 1 :  

Run

public class Main{
    public static void main(String[] args) {
        
        //declaring variables
        double x = 50.3;
        double y = 50.5;
        double z = 50.7;
        double e = 0.0;
        
       
        //printing output for round method.
        System.out.println("Math.round(" + x + ") = " + Math.round(x));
        System.out.println("Math.round(" + y + ") = " + Math.round(y));
        System.out.println("Math.round(" + z + ") = " + Math.round(z));
        System.out.println("Math.round(" + e + ") = " + Math.round(e));
    }
}

Output :

Math.round(50.3) = 50
Math.round(50.5) = 51
Math.round(50.7) = 51
Math.round(0.0) = 0 

Example 2  :  

Run
public class Main {
	public static void main(String args[])
	{
	// declaring variables
	float x = 45.74f;

	// printing the closest int for flaot value.
	System.out.println(Math.round(x));
		
	float y = -21.14f;

	// printing the closest int for flaot value.
	System.out.println(Math.round(y));
		
	double positiveInfinity = Double.POSITIVE_INFINITY;

	// printing the closest int for positive infinity  value.
	System.out.println(Math.round(positiveInfinity));
		
	}
}

Output :

46
-21
9223372036854775807

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription