File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Math.round() onK&B Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Math.round() onK&B" Watch "Math.round() onK&B" New topic

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.


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

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 ...

Hopefully you can figure it out from here ...
Glen Fernandes

Joined: Jan 28, 2005
Posts: 5

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).

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:
subject: Math.round() onK&B
It's not a secret anymore!