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

34,543

Solution 1

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.

Solution 2

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

Solution 3

To convert floor division to ceiling division:

(numerator + denominator-1) / denominator

To convert floor division to rounding division:

(numerator + (denominator)/2) / denominator

Solution 4

You can always cast first:

Math.ceil((double)3/2)

Solution 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) );
Share:
34,543
Rig Veda
Author by

Rig Veda

Updated on July 13, 2020

Comments

  • Rig Veda
    Rig Veda almost 4 years

    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.

  • Gil Vegliach
    Gil Vegliach over 7 years
    First is also equivalent to: ceil(n/d) = fl((n - 1)/d) + 1
  • Anirudh
    Anirudh about 4 years
    Simple, and saves you the trouble of converting to a double I like it.