Java Rounding value round() Function

java.lang.Math class comes with many methods to do simple basic numeric operations. One such one is round() method which returns always a nearest rounded integer/long value of a number. With round() method, a float or double value can be rounded off. Read down.

One advantage of Math class methods is that they are declared as static so that they can be called without the need of object creation.

Following is the Math class signature as defined in java.lang package.

public final class Math extends Object

round() method is overloaded 2 times in Math class.

  1. long round(double a): Floating-point value is rounded off to a long value. 0.5 and above is rounded to nearest higher long value and below 0.5 is rounded off to the nearest lower long value.
  2. int round(float a): Floating-point value is rounded off to an integer value. 0.5 and above is rounded to nearest higher int value and below 0.5 is rounded off to the nearest lower int value.

Or to say, add 0.5 to the parameter, take the floor value, cast to integer and you get the result.

Notice, if the parameter is double, long is returned and if float, int is returned. Observe the next example and screenshot.

For example:

1. The value 24.49 is returned as 24
2. The value 24.50 value is returned as 25
3. The value -24.49 is returned as -24
4. The value -24.51 value is returned as -25

Example on Java Rounding value round() Function illustrating the above two methods.
public class MathFunctionDemo
{
  public static void main(String args[])
  {
   double d1 = 24.49;
   double d2 = 25.01;
   double d3 = -25.01;
  
   long result1 = Math.round(d1);

   System.out.println("\nEvaluating double values:");
   System.out.println("Math.round(24.49) is " + result1);   
   System.out.println("Math.round(25.01) is " + Math.round(d2)); 
   System.out.println("Math.round(-25.01) is " + Math.round(d3));

   float f1 = 24.49f;
   float f2 = 25.01f;
   float f3 = -25.01f;

   int result2 = Math.round(f1);

   System.out.println("\nEvaluating float values:");
   System.out.println("Math.round(24.49f) is " + result2);   
   System.out.println("Math.round(25.01f) is " + Math.round(f2));   
   System.out.println("Math.round(-25.01f) is " + Math.round(f3));  
  }
}


Java Rounding value round() Function
Output screen om Java Rounding value round() Function

Leave a Comment

Your email address will not be published.