Wednesday, July 3, 2024
HomeLanguagesJavarint() in Java (Rounding to int)

rint() in Java (Rounding to int)

In Java, Math.rint() is an inbuilt method that is used to round off the floating-point argument to an integer value (in floating-point format). 

Syntax of rint() Method

Math.rint(double n);

Parameters

The rint() function takes a mandatory single argument value to round. 

Returns

A double value is returned. This method returns the integer that is closest in value to the argument.

The complexity of the method

Time Complexity: O(1)
Space Complexity: O(1)

Example of Math rint() Method

Example 1:

Program demonstrating the use of rint() function.

Java




// Java program for implementation of
// rint() method
import java.util.*;
class GFG {
 
    // Driver Code
    public static void main(String args[])
    {
        double x = 12.6;
        double y = 12.2;
 
        // rint() method use to return the
        // closest value to the argument
        double rintx = Math.rint(x);
        double rinty = Math.rint(y);
 
        // Prints the rounded numbers
        System.out.println(rintx);
        System.out.println(rinty);
    }
}


Output

13.0
12.0

Exception: In case of 0.5 at decimal places it will round off to nearest even double value. 

Example 2: 

Program explaining the exceptions 

Java




// Java program for implementation of
// rint() method exception
import java.util.*;
class GFG {
 
    // Driver Code
    public static void main(String args[])
    {
        double x = 1.5;
        double y = 2.5;
 
        // rounds upto 2 which is the nearest
        // even double value
        double rintx = Math.rint(x);
        double rinty = Math.rint(y);
 
        System.out.println(rintx);
        System.out.println(rinty);
    }
}


Output

2.0
2.0

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments