• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Math Round

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What will be the output of the following
1)Math.Round(-4.6)
2)Math.Round(-4.5)
3)Math.Round(4.6)
4) Math.Round(4.5)
1) = -5 ? How does it happen ?
2) = -4 ? How does it happen ?
3) = 5
4) = 5
Can anyone please explain.
Mahesh
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(1) -4.6 + 0.5 = -4.1
The closest integer to - 4.1 which is not greater than -4.1 is -5.
(2) -4.5 + 0.5 = -4.0
The closest integer to -4.0 which is not greater than -4.0 is -4.
etc.
From the API:
round
public static long round(double a)
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)
Special cases:
If the argument is NaN, the result is 0.
If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal
to the value of Long.MIN_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is
equal to the value of Long.MAX_VALUE.

floor
public static double floor(double a)
Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a
mathematical integer. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot
Gang
 
Without deviation from the norm, progress is not possible - Zappa. Tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic