Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!

# using the math class for rounding numbers

Leroy J Brown
Ranch Hand
Posts: 71
Ok,
I'm working on a project and I need to write a method that takes an input number, divides by three and then returns the number that is the closest mathematical integer above it. So a method that rounds up should be involved. I'm trying to test out the Math.ceil and Math.floor methods but I'm confused.

7 / 3 is 2.333~

So I don't understand why both

AND

are returning 2.0. Shouldn't Math.ceil return 3.0?

marc weber
Sheriff
Posts: 11343
Originally posted by Tristan Rouse:
...
7 / 3 is 2.333~...

Not in Java, where 7 and 3 are each ints, and so the result of this operation is also an int. (Truncated.)

To get a floating-point result, at least one of these values must be a floating-point type.

Robin Lane
Ranch Hand
Posts: 76
"When you divide an int value by another int value, you get an int value. The computer doesn't round... (it) chops off any remainder... If you need a decimal answer, make either (or both) of the numbers you're dividing double values." Barry Burd, Author, Beginning Programming with Java for Dummies

I believe this means you must change your numbers to decimals, then divide, then round.

Leroy J Brown
Ranch Hand
Posts: 71
So can I cast the numbers some how like this...

or do I have to initialize them as variables such as

??

marc weber
Sheriff
Posts: 11343
If you are using literals, the quickest way would be to just add a decimal to one of them...

7.0 / 3

Otherwise, defining a variable as type double would work.

(You probably don't want to "cast," because then you are boxing and unboxing Double objects for no reason.)

Leroy J Brown
Ranch Hand
Posts: 71
Thanks friends. I can't tell you how helpful this forum is to me.

 Don't get me started about those stupid light bulbs.