Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

You can always cast first:

Math.ceil((double)3/2)

To convert floor division to ceiling division:

(numerator + denominator-1) / denominator

To convert floor division to rounding division:

(numerator + (denominator)/2) / denominator

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) );

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

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.

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.

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?

below fragment works with negative integers as well:

public static int divRoundUp(int x, int n) {
    if (n<=0) throw new RuntimeException("conceived wt. pos. dividers (was:"+n+")");
    int ret = (x+(n-1)*(x>0?1:0))/n;
    return ret;
}

I like Randy Proctor's answer the best. Here in more detail:

If you want to do real rounding (i.e. 3/2 -> 2, but 17 / 7 -> 2) with integers > 0: use (dividend + (divisor / 2)) / divisor instead of dividend / divisor.

If dividend can be any integer (i.e. negative allowed): (dividend >= 0) ? ((dividend + divisor / 2) / divisor) : ((dividend - divisor / 2) / divisor).

If dividend is any integer and divisor any integer but 0: (dividend >= 0) ? ((dividend + Math.abs(divisor) / 2) / divisor) : ((dividend - Math.abs(divisor) / 2) / divisor).

(Note that the addition and substraction can cause a wraparound that otherwise wouldn't occur, rendering the result incorrect.)

Here is a method I created to handle int division without using Math Round and casting to float. This works for positive and negative numbers. It works by adding half of the denominator to offset the rounding down

public static int div_Int(int num, int den){
    if(num > 0 && den > 0 || num < 0 && den < 0 ){
        return ((2*num)+ den)/(2*den);  
    }else{
        return ((2*num)- den)/(2*den);
    }

}

If you want to just divide by 2, you can do:

n - n / 2

And in general:

(n - 1) / d + 1 == (n + d - 1) / d

This holds for non-negative integers. How to extend it to negative integers depends on what you mean with "does rounding this way". Integer division is rounded towards zero, whereas Math.ceil() rounds up and Math.floor() rounds down. For example n / 2 != (int) Math.floor(n / 2.0) for n == -5.

If you want to always round up, you can use Math.ceil() as in this answer.

If you really want to avoid using ceil and casting, here is a little method that accomplishes the same thing.

public int findCeil(int X, int Y) {
        if (X % Y == 0){
            return X / Y;
        } else {
            return X / Y + 1;
        }
    }

Have you tried Math.floor() ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top