Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Ben Gao
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ben Gao
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic