Mohamad Samy

Ranch Hand

Posts: 98

posted 4 years ago

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

posted 4 years ago

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,,

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,,

posted 4 years ago

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.

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. |