Math.round...(for -ve no.)

public class math { public static void main(String a[]) { System.out.println(Math.round(-2.5));// o/p is -2....line 1 System.out.println(Math.round(-2.4));// o/p is -2....line 2 System.out.println(Math.round(-2.6));// o/p is -3....line 3 System.out.println(Math.round(2.5)); // o/p is 3...as expected. System.out.println(Math.round(2.4)); // o/p is 2...as expected. System.out.println(Math.round(2.6)); // o/p is 3...as expected. } } round returns a long for double, returns an int for float. (closest int or long value to the argument) The result is rounded to an integer by adding � , taking the floor of the result, and casting the result to type int / long. NOw...look at the o/p of line 1 and line 3 (-2.5 is giving -2 whereas line -2.6 is giving -3.) . As fer as in +ve no. this is not the rule. In positive nos. both 2.5 and 2.6 will give 3.Now look at line 2 also. same problem here. Can any1 tell me what is real rule for -ve no's roundness.. I am simply not geting any rule?? Thanks In Advance. <marquee> Ratul Banerjee </marquee>

Thanks Art can u tell me then why line 3 is showing -3 on the stnd. o/p.

Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241

posted May 02, 2001 12:57:00

0

Because -3 is the int that is closer to the float -2.6. As I mentioned earlier, as a general rule, Math.round() returns the integral value that is closer to the input value. The int closer to -2.6 is -3. Similarly, the int closer to +2.6 is +3, so Math.round( +2.6 ) = 3. Now that we've established that round() returns the integral value that's closer to the input, the question presents itself, what is the behavior if the input value is equidistant from its neighboring integral values? Which int is "closer" then? That is, if float f = ( 2n + 1 ) / 2 for integral n, what is Math.round( f )? The answer is, for these special cases where round()'s input is "something-point-five", round() rounds up towards positive infinity. Maybe this illustration will help: