wood burning stoves 2.0*
The moose likes Java in General and the fly likes Math issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Math issue" Watch "Math issue" New topic
Author

Math issue

Sarah Shay
Greenhorn

Joined: Jan 04, 2005
Posts: 14
Hi,

Im trying to divide 2 numbers lets say 127 by 50. When I do I get a value of 3 returned. However I want 4 to be returned, asin I want the remainder to be recognised. How can I do this?

Thanks
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hmm. 127 / 50 is 2, not 3 or 4, with a remainder of 27, so I'm not exactly sure what you're after here.

But if you divide two integers, you get the quotient as an integer, ignoring the remainder, and you can use the "%" operator to get just the remainder -- i.e.,

127 / 50 --> 2
127 % 50 --> 27


[Jess in Action][AskingGoodQuestions]
Sarah Shay
Greenhorn

Joined: Jan 04, 2005
Posts: 14
Yes its 2.5 roughly. But I want to round this up to 3 so I dont lose the decimal at the end
M Beck
Ranch Hand

Joined: Jan 14, 2005
Posts: 323
you could cast the values to doubles, so as to do a floating-point division, then round up, then after that convert back to integers if needed. the Math class has some rounding functions you might find useful.

or you could do an integer division the way you are, then do aseparate modulus operation to find the remainder, and add 1 to the result of the division if needed depending on what the modulus was. it's your choice which of the methods is more complicated and roundabout, i think.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
If you need the decimal places, you should probably use floats or doubles to start with instead of just ints. Then if you need to, you can round these off from there.

Layne


Java API Documentation
The Java Tutorial
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
To round up integer division add divisor-1 before dividing.

127 + 9 / 10 = 13

127 + 49 / 50 = 3


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Math issue