23

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Rig Veda
  • 801
  • 2
  • 10
  • 17
  • 3
    Are you looking for only rounding 0.5 up? or rounding 0.3 up, etc? – Jerod Venema Jul 02 '09 at 13:16
  • @jvenema: Exactly - most of the proposed solutions assume anything over 1.0 should round to 2. For example, 7/3 is 2.333 but would round to 3. However, given the example from the OP, it's not clear whether this is desired or not. – GalacticCowboy Jul 02 '09 at 15:00
  • I feel, since he initially tried ceil, that was the functionality he was looking for. – jjnguy Jul 02 '09 at 15:07
  • yes , that was what I was looking for. Just that I passed wrong arguments. Thanks again everyone. :) – Rig Veda Jul 02 '09 at 15:34
  • Unclear what wanted, but apparently a duplicate of this clearer question: http://stackoverflow.com/questions/7446710/how-to-round-up-integer-division-and-have-int-result-in-java – Raedwald Nov 08 '13 at 15:46
  • Possible duplicate of http://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division – Raedwald Nov 08 '13 at 15:49
  • @RigVeda: added a simplification for the case where the division is by 2. – Gil Vegliach Jul 28 '17 at 20:09

15 Answers15

57

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
  • 136,852
  • 53
  • 295
  • 323
51

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
  • 7,199
  • 2
  • 30
  • 33
  • I actually like this method more as I don't need to import Math, cast etc etc.. Thanks! – Mat May 21 '12 at 09:00
  • 4
    @Mat On the other hand anyone reading your code will find it harder to figure out what you were doing and why. That's a much stronger argument against doing this than any of the ones you listed for it. However you can extract it into a properly named method and then it's fine. – biziclop Oct 15 '12 at 22:55
14

To convert floor division to ceiling division:

(numerator + denominator-1) / denominator

To convert floor division to rounding division:

(numerator + (denominator)/2) / denominator
Randy Proctor
  • 7,396
  • 3
  • 25
  • 26
12

You can always cast first:

Math.ceil((double)3/2)
PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
5

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
  • 342,105
  • 78
  • 482
  • 720
4

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

sisve
  • 19,501
  • 3
  • 53
  • 95
3

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.

Pesto
  • 23,810
  • 2
  • 71
  • 76
Samuel Carrijo
  • 17,449
  • 12
  • 49
  • 59
2

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
  • 23,810
  • 2
  • 71
  • 76
1
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,253
  • 2
  • 23
  • 39
1

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.

Gil Vegliach
  • 3,542
  • 2
  • 25
  • 37
1

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;
}
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331
1

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;
        }
    }
0

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

}
pt123
  • 2,146
  • 1
  • 32
  • 57
0

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

DaveFar
  • 7,078
  • 4
  • 50
  • 90
-4

Have you tried Math.floor() ?

Tony Miller
  • 9,059
  • 2
  • 27
  • 46