File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using the math class for rounding numbers

 
Leroy J Brown
Ranch Hand
Posts: 71
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
What am I missing please?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks friends. I can't tell you how helpful this forum is to me.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic