math
Round float and double numbers
With this example we are going to demonstrate how to round float and double numbers using round()
method of Math. The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. In short, to round float and double numbers you should:
- Use
round(float a)
method to get the closestint
to the argument, with ties rounding up. - Use
round(double a)
method to get the closestlong
to the argument, with ties rounding up.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class RoundFloatDouble { public static void main(String args[]) { // All the examples return the closest int/long to // the argument of round static method System.out.println(Math.round(76.3)); System.out.println(Math.round(76.7)); System.out.println(Math.round(-53.4)); System.out.println(Math.round(-53.6)); } }
Output:
76
77
-53
-54
This was an example of how to round float and double numbers using round()
method of Math in Java.