The Math.round()
method in Java is used to round a number to its closest integer. This is done by adding 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:
Integer.MIN_VALUE
, then the function returns Integer.MIN_VALUE
.Integer.MAX_VALUE
, then the function returns Integer.MAX_VALUE
.Let’s see the implementation of the Math.round( )
method:
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));}}
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));}}
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