• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

inconsistent round() function

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I assumed that the output should be either
5 & -5
Or
4 & -4
But the output are 5 & -4 !
API says that the return value is the value of the argument rounded to the nearest long value.
But what's the nearest long value in this case? it doesn't say. In the case that the distances to 2 adjacent long values are equal,it should round upword?
Any comments?
Regards,
James
[This message has been edited by James Du (edited June 06, 2001).]
 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is the expected behavior. See what the API says


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)


Applying this formula to your numbers,
round( 4.5 )
= floor( 4.5 + 0.5d )
= floor( 5.0 )
= 5
round( (-4.5 )
= floor( -4.5 + 0.5d )
= floor( -4.0 )
= -4

Hope that helps!
------------------
Ajith Kallambella M.
Sun Certified Programmer for the Java�2 Platform.
IBM Certified Developer - XML and Related Technologies, V1.
 
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you're losing sight of the fact that -4>-5
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
so that means the behavior of round and rint are DIFFERENT when deal with x.5 (x >= 0), but same when deal with x.5 (x < 0). Sun should make them the same to avoid confuse.
 
I have gone to look for myself. If I should return before I get back, keep me here with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic