1

I am trying to do simple math. a=5, b=a/2 &(round up), which has to be 5/2 = 3 when I round up , c=b-a, 3-5=2. my question when I divide 5/2 and round up I got 2 instead of 3 for b. can some one help me how I can round up and get 3? Thanks

int a=5;

int b=(int)Math.ceil(a/2);

int c=b-a;


System.out.println(b);

System.out.println(c);
Cootri
  • 3,806
  • 20
  • 30

2 Answers2

4

you should use floating-point value of 2 instead of integer in this line:

int b = (int) Math.ceil(a / 2f);//also you can use "2.0" or "2d" instead of "2f"

your version uses int division (which produces int value of 2) and 2f constant forces to use floating-point division and promote a value to float (after it division produces float value of 2.5)

It is possible because of JLS spec for Multiplicative Operators:

Binary numeric promotion is performed on the operands (§5.6.2)

And that is how numeric promotion works for int and float division operands in our case:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules: If either operand is of type double, the other is converted to double. Otherwise, if either operand is of type float, the other is converted to float.

Cootri
  • 3,806
  • 20
  • 30
3

You can use a little trick to get things faster:

int b =(a + 1) / 2;

Since you are dividing with 2, in case the number is odd with + 1, you'll get exact value for upper rounding. And if number is even with + 1 rounding will give the half of it as expected.

EDIT

Or in general, if you want to calculate Math.ceil(a / b) you can do it with following formula : (a + b - 1) / b, assuming a and b being positive.

user987339
  • 10,519
  • 8
  • 40
  • 45