File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# Math.round() onK&B

M Rama
Ranch Hand

Joined: Mar 04, 2005
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

Joined: Apr 16, 2005
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

Joined: Jan 28, 2005
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

Joined: Apr 10, 2005
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

SCJA 1.0 (98%), SCJP 1.4 (98%)

I agree. Here's the link: http://aspose.com/file-tools

subject: Math.round() onK&B