# Math.Round

gayatri ganesh

Greenhorn

Posts: 28

posted 12 years ago

Hi,

I have a doubt in the following question.

What is the output of following

{

float f4 = -5.5f;

float f5 = 5.5f;

float f6 = -5.49f;

float f7 = 5.49f;

System.out.println("Round f4 is " + Math.round(f4));

System.out.println("Round f5 is " + Math.round(f5));

System.out.println("Round f6 is " + Math.round(f6));

System.out.println("Round f7 is " + Math.round(f7));

}

a)Round f4 is -6

Round f5 is 6

Round f6 is -5

Round f7 is 5

b)Round f4 is -5

Round f5 is 6

Round f6 is -5

Round f7 is 5

Correct answer is b)

I understood the answer for f5,f6 and f7 but isn't f4 = -4 ? Please explain. Thank you

I have a doubt in the following question.

What is the output of following

{

float f4 = -5.5f;

float f5 = 5.5f;

float f6 = -5.49f;

float f7 = 5.49f;

System.out.println("Round f4 is " + Math.round(f4));

System.out.println("Round f5 is " + Math.round(f5));

System.out.println("Round f6 is " + Math.round(f6));

System.out.println("Round f7 is " + Math.round(f7));

}

a)Round f4 is -6

Round f5 is 6

Round f6 is -5

Round f7 is 5

b)Round f4 is -5

Round f5 is 6

Round f6 is -5

Round f7 is 5

Correct answer is b)

I understood the answer for f5,f6 and f7 but isn't f4 = -4 ? Please explain. Thank you

Jay Pawar

Ranch Hand

Posts: 411

posted 12 years ago

Math.round(-5.5f) is internally calculated as (int)Math.floor(-5.5 + 0.5 ) which is (int)Math.floor(-5.0) = -5

Hence the answer is -5

Hope this helps you...

[ January 18, 2005: Message edited by: Jay Pawar ]

Original Post Gayatri Ganesh

I understood the answer for f5,f6 and f7 but isn't f4 = -4 ? Please explain

Math.round(-5.5f) is internally calculated as (int)Math.floor(-5.5 + 0.5 ) which is (int)Math.floor(-5.0) = -5

Hence the answer is -5

I would say, if you know how to calculate Math.floor function correctly then Math.round() should be very easy. Math.round(x) is equivalent to

(int)Math.floor(x + 0.5) if x is float.

(long)Math.floor(x + 0.5) if x is double.

Hope this helps you...

[ January 18, 2005: Message edited by: Jay Pawar ]

Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.

posted 12 years ago

Java's API documentation is an excellent resource...

http://java.sun.com/j2se/1.5.0/docs/api/index.html

Find the Math class, then check the documentation for the round methods.

http://java.sun.com/j2se/1.5.0/docs/api/index.html

Find the Math class, then check the documentation for the round methods.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." *~Joe Strummer*

sscce.org