Alex Rivera | Logout

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

Asked 2009-07-02T13:06:47.300
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.

Edit
Report

4 Answers

12

You can always cast first:

Math.ceil((double)3/2)
answered 2009-07-02T13:08:19.077
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) );
answered 2009-07-02T13:11:40.863
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.

answered 2009-07-02T13:10:13.393
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?

answered 2009-07-02T13:13:39.690

Your Answer