Java Math round() Method
The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity.
Syntax:
- public static int round(float a)
- public static long round(double a)
Parameters:
The parameters ‘a’ represents the floating –point number whose rounded value is to be determined.
Return Value:
The round() method returns the rounded value of the argument to its nearest long or int value.
Special cases are as follows:
- The result is 0, if the argument is NaN.
- The result is Long.MIN_VALUE, if the argument is negative infinity or any value less or equal to Long.MIN_VALUE.
- The result is Long.MAX_VALUE, if the argument is positive infinity or any value greater or equal to Long.MAX_VALUE.
Example 1:
public class JavaMathRoundExample1 { static int i=1; //returns the rounded value of the argument to its nearest long public static void main(String[] args) { double a=67.4; double b=67.5; System.out.println(i++ +". " +Math.round(a)); System.out.println(i+". "+Math.round(b)); } }
Output:
1. 67 2. 68
Example 2:
public class JavaMathRoundExample2 { static int i=1; // result is 0, if the argument is NaN public static void main(String[] args) { double a=Double.NaN; System.out.println(i++ +". " +Math.round(a)); } }
Output:
1. 0
Example 3:
public class JavaMathRoundExample3 { static int i=1; // result is Long.MIN_VALUE, if the argument is negative infinity or any value less or equal to Long.MIN_VALUE. public static void main(String[] args) { double a=Double.NEGATIVE_INFINITY; System.out.println(i++ +". " +Math.round(a)); } }
Output:
-9223372036854775808
Example 4:
public class JavaMathRoundExample4 { static int i=1; //result is Long.MAX_VALUE, if the argument is positive infinity or any value greater or equal to Long.MAX_VALUE. public static void main(String[] args) { double a=Double.POSITIVE_INFINITY; System.out.println(i++ +". " +Math.round(a)); } }
Output:
9223372036854775807
Example 5:
public class JavaMathRoundExample5 { static int i=1; // returns the rounded value of the argument to its nearest int. public static void main(String[] args) { float a=0.5f; System.out.println(i++ +". " +Math.round(a)); } }
Output:
1