Java Rounding to double Math rint()


java.lang.Math class comes with many methods to do simple basic numeric operations. One such one is rint() method which returns the nearest rounded double value of a number passed as parameter.

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

Following is the signature of rint() method in Math class.

  • double rint(double a): Returns the nearest double value rounded.

For example, rint(2.01) returns 2.0, and rint(2.90) returns 3.0

Notice, the method takes a double value and returns a double value.

Example on Java Rounding to double Math rint() illustrates the above two methods.
public class MathFunctionDemo
{
  public static void main(String args[])
  {
     System.out.println("rint() with positive values:");
     System.out.println("rint(2.01) is " + Math.rint(2.01)); 
     System.out.println("rint(2.50) is " + Math.rint(2.50)); 
     System.out.println("rint(2.51) is " + Math.rint(2.51)); 
     System.out.println("rint(2.99) is " + Math.rint(2.99)); 

     System.out.println("\nrint() with negative values:");
     System.out.println("rint(-2.01) is " + Math.rint(-2.01)); 
     System.out.println("rint(-2.99) is " + Math.rint(-2.99)); 
  }
}


Java Rounding to double Math rint()
Output screen on Java Rounding to double Math rint()

Let us study more:

Find the difference of rint() and round() methods

System.out.println("rint(2.50) is " + Math.rint(2.50)); // prints 2.0
System.out.println("round(2.50) is " + Math.round(2.50)); // prints 3

More you can find the differences in Difference of Math.rint(double) and Math.round(double)

Leave a Comment

Your email address will not be published.