# Rounding of numbers in Java

There is the class Math in the package java.lang, which contains 3 methods of rounding of numbers with floating point to the nearest integer:

1.Math.round ()

2.Math.floor ()

3.Math.ceil()

###### The names of these methods are self-explanatory.

Let’s take a look at the example below and see how these methods work:

###### Example №1

If you run this code on your computer, you will see the following in the console:

5
5.0
6.0

1. Math.round () - this method rounds a number to the nearest integer.

And indeed, at first we have 5.25, but the method returns 5, because it is the nearest integer number. If, for example, we rounded 8.75 with this method, we would get 9 - because it is the nearest integer number.

Also please note, that this method returns a value of the int type, i.e. an integer. At first we have 5.25, and the methods returns 5 instead of 5.0.

2. Math.floor () - this method rounds a number downward to the nearest integer.

And indeed, at first we have 5.25, and the nearest number downward is 5.0. And if we, for example, rounded the number 8.75 with the help of this method, we would get 8.0, because it is the nearest number downward.

Now you understand why this method is called floor.

Also please note, that this method returns the value of the double type. At first we have the number 5.25, and after the rounding we get 5.0 – the double type.

3. Math.ceil() - this method rounds a number upward to its nearest integer. We have 5.25, and this method returns 6.0. Even if we had 5.01, this method would still return 6.0, because it is the nearest number upward.

That’s why this method is called ceil – from the word ceiling. Also please note, that this method returns a value of the double type.

Below is the table with diagrammatical representation:

You also should know about the methods Math.random(), Math.max () и Math.min(). About these methods you can read in our articles:

offline 5 hours