• 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

Math.round() onK&B

 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
K&B says, the algorithm for round() is add 0.5 and truncate to the nearest integer.

While this works for +ve numbers, -ve causes me problems.

Math.round(-2.9);



gives me the answer of -3. Where as using the algorithm:

-2.9 + .5 = -2.4 and truncating gives me -2.



Can anyone explain this?
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class round{
public static void main(String[] argv){
System.out.println("" + Math.round(-2.9));
System.out.println("" + -2.9 + 0.5 );
System.out.println("" + Math.round(-2.9 + 0.5));

}
}

Gives you the output ...
-3
-2.90.5
-2

Hopefully you can figure it out from here ...
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey,

Think of Math.round(x) as being equivalent to a Math.floor(x + 0.5)
So Math.round(-2.9) would equal Math.floor(-2.4)

And you should know that the floor method will return the largest integer which is less than or equal to its argument (so in this case -3).

Regards,
Glen
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One source of confusion is the thought of "truncating" the digits that are to the right of the decimal point. Don't think of it that way because that is not what's happening. Just remember, as the other people posting here have pointed out, that the algorithm for Math.round() is to add 0.5 and then perform a Math.floor(), which returns the nearest integer less than or equals to the value passed.

-2.9 + .5 = -2.4
Math.floor(-2.4) lowers the result to -3.0
Since Math.round(double) returns a long, the final result returned is equivalent to -3L
 
Story like this gets better after being told a few times. Or maybe it's just a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic