This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Math Round

Mahesh Bansal
Ranch Hand
Posts: 82
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
Mahesh

Cindy Glass
"The Hood"
Sheriff
Posts: 8521
(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.

Gang Hong
Greenhorn
Posts: 7
Thanks a lot
Gang