Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 368
Rig Veda Avatar asked Jul 02 '09 13:07

Rig Veda


3 Answers

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.

like image 143
jjnguy Avatar answered Sep 29 '22 05:09

jjnguy


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
like image 35
Tal Pressman Avatar answered Sep 29 '22 05:09

Tal Pressman


To convert floor division to ceiling division:

(numerator + denominator-1) / denominator

To convert floor division to rounding division:

(numerator + (denominator)/2) / denominator
like image 30
Randy Proctor Avatar answered Sep 29 '22 05:09

Randy Proctor