• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Math function doubt

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

Answer is given as -5,6,-5,5.
My doubt is the 3 rd output.
Math.round(-5.49f)--- how come this is -5. As per my understanding it is -6.
Could anyone please explain this. Its confusing me a lot.


Thanks.
 
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
float f6 = -5.49f;

round always rounds a float or a double to the nearest integer or a long respectively. If it is right in the middle like 5.5, it rounds to the nearest large integer.
For the above example, -5.49 is closer to -5 than it is to -6. Hence , the output.

The answer would be -6 if f6 = -5.51f.

Get it?
 
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vidyavathi,
If you look the underlying implementation of round , it is nothing but adding 0.5f to the number and then perform floor on the result. In your case,

I know this round function is confusing sometimes, but if you know floor method correctly then you will never fail in getting answer for round function. Hope this helps ya.
[ November 11, 2004: Message edited by: Jay Pawar ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic