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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# round method doesn't work

Ranch Hand
Posts: 98
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.

Sheriff
Posts: 3015
12
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?

Ranch Hand
Posts: 98
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,,

Bartender
Posts: 612
7
Even easier, why not just add .5 to the floating point number then cast to int.

Greg Charles
Sheriff
Posts: 3015
12
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.