This article will demonstrate how to round up in Java.
How to Round Up in Java?
In Java, there are two methods that can be utilized to round up the values:
- Math.ceil()
- Math.round()
Let’s use both of them one by one!
How to Round Up in Java Using Math.ceil() Method?
“ceil” is derived from the word “ceiling”. The “ceil()” method belongs to the Java “Math” class and rounds up the number towards its closest integer. It outputs the “double” type, a decimal value greater than or equal to the parameter.
Syntax
Math.ceil(number)
Here, the Math.ceil() method will round up the added “number” and return the double-type decimal value.
Example
Let’s see an example to round up the decimal number using the “Math.ceil()” method:
Math.ceil() method will round up the value “9.02” to “10”. As we discussed, the ceil() method returns the number into its nearest integer:
Output
Let’s head towards the next method!
How to Round Up in Java Using Math.round() Method?
The Java Math class has one more method named “round()” that is also utilized to round up the mathematical values towards their closest integer. This method returns the “integer” type value.
To round-up, the “Math.round()” method checks the first decimal value. If it is in between “0-4”, it will return the integer value. If it is in the “5-9” range, the Math.round() method will round up the decimal value to the integer value.
Syntax
The syntax of the Math.round() method is:
Have a look at the provided example to learn more about the usage of the Math.round() method.
Example 1
In this example, we have created a variable named “number” having “9.02” as its value:
Math.round() method will round up the specified variable value to “9” because it is the closest integer of “9.02”:
Output
Example 2
Here, we have a decimal “number” with the value “6.72”, which we want to round up using the Math.round() method:
Math.round() method will print integer value “7” because 7 is the closest integer of “6.72”:
Output
We have compiled all the basic instructions on how to round up in Java.
Conclusion
To round up in Java, you can use Math.ceil() and Math.round() methods. Math.ceil() method returns double type decimal value while Math.round() returns integer type value. Both of these methods are mainly used to make long, problematic numbers easier for better understanding and calculating. This article discussed the methods to round up the decimal values in Java with detailed examples.