Win a copy of Design for the Mind this week in the Design forum!

Math.round() onK&B

M Rama
Ranch Hand
Posts: 91
K&B says, the algorithm for round() is add 0.5 and truncate to the nearest integer.

While this works for +ve numbers, -ve causes me problems.

Math.round(-2.9);

gives me the answer of -3. Where as using the algorithm:

-2.9 + .5 = -2.4 and truncating gives me -2.

Can anyone explain this?

Tej Vattel
Greenhorn
Posts: 3
class round{
public static void main(String[] argv){
System.out.println("" + Math.round(-2.9));
System.out.println("" + -2.9 + 0.5 );
System.out.println("" + Math.round(-2.9 + 0.5));

}
}

Gives you the output ...
-3
-2.90.5
-2

Hopefully you can figure it out from here ...

Glen Fernandes
Greenhorn
Posts: 5
Hey,

Think of Math.round(x) as being equivalent to a Math.floor(x + 0.5)
So Math.round(-2.9) would equal Math.floor(-2.4)

And you should know that the floor method will return the largest integer which is less than or equal to its argument (so in this case -3).

Regards,
Glen

Joe Sondow
Ranch Hand
Posts: 195
One source of confusion is the thought of "truncating" the digits that are to the right of the decimal point. Don't think of it that way because that is not what's happening. Just remember, as the other people posting here have pointed out, that the algorithm for Math.round() is to add 0.5 and then perform a Math.floor(), which returns the nearest integer less than or equals to the value passed.

-2.9 + .5 = -2.4
Math.floor(-2.4) lowers the result to -3.0
Since Math.round(double) returns a long, the final result returned is equivalent to -3L