In this guide, we will discuss the difference between rint()
and round()
method in Java. Both of these methods belong to the Math class of Java. These methods are used for rounding numbers, however the rules they follow are bit different, especially when the number is exactly halfway between two integers.
Example: For the number 2.5, both these methods produce different output. Integers 2 and 3 are equally close to 2.5.
Math.rint(2.5) returns 2.0, because 2 is closest even integer
Math.round(2.5) returns 3, because 3 is away from zero compared to 2
Math.rint
Math.rint(double a)
returns the double value nearest to the argumenta
, and this returned value should be an integer. If two integers are equally close, it rounds to the even integer.
Math.round
Math.round(double a)
returns the long value nearest to the argumenta
, and this returned value should be an integer. If two integers are equally close to the argument, it rounds to the number away from zero.
Example Code: rint() vs round()
public class RintVsRoundExample {
public static void main(String[] args) {
double[] values = { 2.3, 2.5, 2.7, -2.3, -2.5, -2.7, 3.5, 4.5, 5.5, -5.5 };
System.out.println("Using Math.rint:");
for (double value : values) {
double rintResult = Math.rint(value);
System.out.println("Math.rint(" + value + ") = " + rintResult);
}
System.out.println("\nUsing Math.round:");
for (double value : values) {
long roundResult = Math.round(value);
System.out.println("Math.round(" + value + ") = " + roundResult);
}
}
}
Output:
Using Math.rint:
Math.rint(2.3) = 2.0
Math.rint(2.5) = 2.0
Math.rint(2.7) = 3.0
Math.rint(-2.3) = -2.0
Math.rint(-2.5) = -2.0
Math.rint(-2.7) = -3.0
Math.rint(3.5) = 4.0
Math.rint(4.5) = 4.0
Math.rint(5.5) = 6.0
Math.rint(-5.5) = -6.0
Using Math.round:
Math.round(2.3) = 2
Math.round(2.5) = 3
Math.round(2.7) = 3
Math.round(-2.3) = -2
Math.round(-2.5) = -2
Math.round(-2.7) = -3
Math.round(3.5) = 4
Math.round(4.5) = 5
Math.round(5.5) = 6
Math.round(-5.5) = -5
Explanation
Math.rint
:- For 2.3, it rounds to the nearest integer, which is 2.0.
- For 2.5, which is exactly halfway between 2 and 3, it rounds to the nearest even integer, which is 2.0.
- For -2.5, it rounds to the nearest even integer, which is -2.0.
- For 3.5 and 4.5, it rounds to the nearest even integer, which is 4.0 in both cases.
Math.round
:- For 2.3, it rounds to the nearest integer, which is 2.
- For 2.5, which is exactly halfway between 2 and 3, it rounds away from zero, which is 3.
- For -2.5, it rounds away from zero, which is -2.
- For 3.5 and 4.5, it rounds to the nearest integers, which are 4 and 5, respectively.
Conclusion: These methods produce different output when the given number is exactly halfway between two integers. In such case, rint() returns nearest even integer, while double() returns an integer which is away from zero (means far from zero).
Leave a Reply