tags:

views:

651

answers:

10

Is there any Java function or util class which does rounding this way: func(3/2) = 2

Math.ceil() doesn't help, which by name should have done so. I am aware of BigDecimal, but don't need it.

+4  A: 

Aint this the usual case of integer division? Try Math.Ceil after casting either number to a floating point type.

Simon Svensson
3/2 already only returns 1 (an int), so Math.ceil() does nothing. +1
AlbertoPL
--> "after casting either number to a floating point type" <--
GalacticCowboy
Integer division returns the largest number that evenly divides. Allowing you to use modulus to get the remainder.
Brian
+3  A: 

You can always cast first:

Math.ceil((double)3/2)
PatrikAkerstrand
+15  A: 

Math.ceil() will always round up, however you are doing integer division with 3/2. Thus, since in integer division 3/2 = 1 (not 1.5) the ceiling of 1 is 1.

What you would need to do to achieve the results you want is Math.ceil(3/2.0);

By doing the division by a double amount (2.0), you end up doing floating point division instead of integer division. Thus 3/2.0 = 1.5, and the ceil() of 1.5 is always 2.

jjnguy
+2  A: 

Math.ceil will help, provided you use floating point numbers. The problem is that 3/2, in integer division, is 1. By the time the value gets to whatever function, be it Math.ceil or something else, the value is simply 1. Any trailing decimal portion is gone.

Pesto
+8  A: 

A bit of black magic, and you can do it all with integers:

// Divide x by n rounding up
int res = (x+n-1)/n
Tal Pressman
Assuming x is positive!
Niki
A: 

Have you tried Math.floor() ?

Tony Miller
This is the opposite behavior of what he wants.
Brian
+3  A: 

In Java, 3/2 = 1 because it uses integer division. There's no function that can "fix" this afterwards. What you have to do is to force a float divison and round up the result:

int result = (int)Math.ceil( ((float)3) / ((float)2) );
Michael Borgwardt
+2  A: 

Many languages "think" like this. If you're dividing an int into an int, then you should get an int (so they truncate and you get 1 as a result).

We all know this is not true, but that's how they work. You can "cheat" them, and do something like casting one of them to a double, or use a double representation: Math.ceil (3.0 / 2) or Math.ceil((double)3/2), as mentioned.

Samuel Carrijo
+1  A: 
if (a % b == 0)
{
  return (a / b);
}
else
{
  return (a / b) + 1;
}

Exploits integer division to do what you want. I don't know of a math function that does this, but why not roll your own?

Brian
+2  A: 

To convert floor division to ceiling division:

(numerator + denominator-1) / denominator

To convert floor division to rounding division:

(numerator + (denominator)/2) / denominator
Randy Proctor