Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Math.rint() vs. Math.round()

Ranch Hand

Joined: Jun 20, 2005
Posts: 110
Hi all,

Is there any difference between the functioning of

public static double rint(double d)
public static long round(double d)

methods in Math class , other then their return type ?
Can someone help me in understanding the line in sun's java documentation for the rint(double d) method "If two double values that are mathematical integers are equally close, the result is the integer value that is even." by giving suitable example ?
[ July 18, 2005: Message edited by: lalit upadheyay ]

SCJP1.4, SCWCD1.4, SCBCD5.0(working on...)
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Take -1.5 as an argument and see what you get.

There are two doubles that are whole numbers and are equally near 1.5, namely 1.0 and 2.0. The even one is 2.0 and that will be returned from Math.rint.
[ July 18, 2005: Message edited by: Barry Gaunt ]

Getting someone to think and try something out is much more useful than just telling them the answer.
Veer Batra
Ranch Hand

Joined: Mar 12, 2001
Posts: 35
rint
public static double rint(double a)Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close to the value of the argument, the result is the integer value that is even. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

round
public static int round(float a)Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. In other words, the result is equal to the value of the expression:

(int)Math.floor(a + 0.5f)Special cases:

If the argument is NaN, the result is 0.
If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
Ranch Hand

Joined: Jun 20, 2005
Posts: 110
Thank you Barry for the perfect example.

subject: Math.rint() vs. Math.round()