wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Math.round(-4.5)=-4; Why? 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(-4.5)=-4; Why?" Watch "Math.round(-4.5)=-4; Why?" New topic
Author

Math.round(-4.5)=-4; Why?

Ben Gao
Greenhorn

Joined: Feb 19, 2002
Posts: 8
Math.round(4.5)=5;Math.round(-4.6)=-5;
Why Math.round(-4.5)=-4??
I am confused!
Thank you!
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
From the API:

Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. In other words, the result is equal to the value of the expression:
(int)Math.floor(a + 0.5f)

Does that answer your question?
Corey
[ March 05, 2002: Message edited by: Corey McGlone ]

SCJP Tipline, etc.
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Math.round(double d) computes and returns the following:
(long)floor(d + 0.5d);
so:
floor(4.5 + 0.5d) = 5
floor(-4.6 + 0.5d) = -5
floor(-4.5 + 0.5d) = -4


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Ben Gao
Greenhorn

Joined: Feb 19, 2002
Posts: 8
Thank you!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Math.round(-4.5)=-4; Why?