M Rama

Ranch Hand

Posts: 91

posted 12 years ago

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:

Can anyone explain this?

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

posted 12 years ago

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

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

posted 12 years ago

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

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

posted 12 years ago

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

-2.9 + .5 = -2.4

Math.floor(-2.4)

Since Math.round(double) returns a long, the final result returned is equivalent to -3L

**less than or equals to**the value passed.-2.9 + .5 = -2.4

Math.floor(-2.4)

**lowers**the result to -3.0Since Math.round(double) returns a long, the final result returned is equivalent to -3L

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