How to round a number in java

The example below show you some methods of the Math class that can be use to round the value of a number.

You can use methods like Math.ceil(), Math.floor() and Math.round() to round the number in java.

Below is the example code showing rounding some number in java.

package com.java.connect.math;
 
//How to round a number in java
public class RoundingValueExample {
 
    public static void main(String[] args) {
        // Declare the number to round
        Double number = 23.7d;
 
        // Using Math.ceil method
        double round1 = Math.ceil(number);
        System.out.println("Rounding up of " + number + " : " + round1);
 
        // Using Math.floor method
        double round2 = Math.floor(number);
        System.out.println("Rounding down of " + number + " : " + round2);
 
        // Get the closest long value to the argument
        // Using Math.round method
        long round3 = Math.round(number);
        System.out.println("Rounding result of " + number + " : " + round3);
 
        // Get the closest int value to the argument
        int round4 = Math.round(number.floatValue());
        System.out.println("Rounding result of " + number + " : " + round4);
    }
}

The output of the above example will be as:

Rounding up of 23.7 : 24.0
Rounding down of 23.7 : 23.0
Rounding result of 23.7 : 24
Rounding result of 23.7 : 24