This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
What will be the output of the following 1)Math.Round(-4.6) 2)Math.Round(-4.5) 3)Math.Round(4.6) 4) Math.Round(4.5) 1) = -5 ? How does it happen ? 2) = -4 ? How does it happen ? 3) = 5 4) = 5 Can anyone please explain. Mahesh
(1) -4.6 + 0.5 = -4.1 The closest integer to - 4.1 which is not greater than -4.1 is -5. (2) -4.5 + 0.5 = -4.0 The closest integer to -4.0 which is not greater than -4.0 is -4. etc. From the API: round public static long round(double a) Returns the closest long 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 long. In other words, the result is equal to the value of the expression: (long)Math.floor(a + 0.5d) 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 Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE. If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.
floor public static double floor(double a) Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer. 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.
"JavaRanch, where the deer and the Certified play" - David O'Meara