How do I round a number?

The example below show you some methods of the Math class that can be use to round the value of a number. These methods are Math.ceil(), Math.floor() and Math.round().

package org.kodejava.example.math;

public class GetRoundingValueExample {

    public static void main(String[] args) {
        Double number = 1.5D;

        //
        // Get the smallest value that is greater than or equal to the
        // argument and is equal to a mathematical integer
        //
        double roundUp = Math.ceil(number);
        System.out.println("Result of rounding up of " + number + " = " + roundUp);

        //
        // Get the largest value that is less than or equal to the
        // argument and is equal to a mathematical integer
        //
        double roundDown = Math.floor(number);
        System.out.println("Result of rounding down of " + number + " = " + roundDown);

        //
        // Get the closest long value to the argument
        //
        long round1 = Math.round(number);
        System.out.println("Rounding result of " + number + " (in long) =  " + round1);

        //
        // Get the closest int value to the argument
        //
        int round2 = Math.round(number.floatValue());
        System.out.println("Rounding result of " + number + " (in int) = " + round2);
    }
}

Here are the result of the program:

Result of rounding up of 1.5 = 2.0
Result of rounding down of 1.5 = 1.0
Rounding result of 1.5 (in long) =  2
Rounding result of 1.5 (in int) = 2
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply