• Post Reply Bookmark Topic Watch Topic
  • New Topic

round method doesn't work  RSS feed

 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a little problem as I want the method here to round the double values as if the number is 9.2 it will be floored to 9 and if the number is 9.8 it will be ceiled to 10 as the following code but there is some logic I can't get.

 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of a second "if", you would be better served with an "else". Now, when you divide a number by 1, you get that same number back, so when you do your remainder operation (%), you'll always end up with 0. Why not try newValue % 1 and see if that works better? Also, there is a Math.round() method, but maybe your assignment is to do rounding without using it?
 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried your option to get newValue % 1 but always floored the value even if the number should be ceiled. and you are right that the example mustn't use any Math class methods.
but if I tried another way and it works as by casting the double newValue to integer number, then use the remainder by dividing the double value over the casted one to compare with .5 on.
as,,
 
Steve Fahlbusch
Bartender
Posts: 612
7
Mac OS X Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even easier, why not just add .5 to the floating point number then cast to int.
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, "% 1" works OK for me for non-negative numbers. Steve's suggestion would also work for non-negatives. All three methods fail to round properly for negative numbers. You might also try 0.8 with your method, and see if you get what you expect.

Also ... and I hate to pile on like this ... but both floor() and ceil() are Math class methods.

 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!