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( -.5)?

 
Tom Adams
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it seem odd that java rounds -.5 to zero?
Is that right?
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check out the API for Math.round(double)
Returns the closest long 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 long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)

So... it behaves just like it's supposed to.
 
Tom Adams
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yea...I read that also. Is it just me or does this seem strange? Just as a check excel and MS SQL Server both feel that -.5 should be rounded to -1. :roll:
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lol yes -- it does seem a little strange... maybe you can write your own method called
long roundTheWayIExpectItToBehave(double d)
and use that??
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic