This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
In K&B book, page 371 following definition is given for Math.round():
The round() method returns the integer closest to the argument. The algorithm is to add 0.5 to the argument and truncate to the nearest integer equivalent.
Going by the above definition: round(8.2) = Nearest integer to (8.2 + 0.5 = 8.7) = 8 round(8.7) = Nearest integer to (8.7 + 0.5 = 9.2) = 9 round(-8.2) = Nearest integer to (-8.2 + 0.5 = -7.7) = -7 //?? (Ans: -8) round(-8.7) = Nearest integer to (-8.7 + 0.5 = -8.2) = -8 //?? (Ans: -9)
But, for negative numbers, if I subtract 0.5 instead of adding, we get the right answers. So, I think it should be add 0.5 to +ve numbers and subtract 0.5 from negative numbers. Also, I don't think 'nearest integer' are the right words to use. I think it should be add 0.5 to +ve numbers or subtract 0.5 from negative numbers and 'discard decimal portion'. Does anyone have a different opinion on this?
The K&B book also says that when if a number's fraction is less than 0.5 then round will work like Math.floot(); When the number's fraction is equal to or greater than 0.5 then round will work like Math.ceil().
When dealing with negative numbers think of them like this: