Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the next higher integer value in java [duplicate]

Tags:

java

math

numbers

I know I can use Math.java functions to get the floor, ceil or round value for a double or float, but my question is -- Is it possible to always get the higher integer value if a decimal point comes in my value

For example

int chunkSize  = 91 / 8 ; 

which will be equal to 11.375

If I apply floor, ceil or round to this number it will return 11 I want 12.

Simply If I have 11.xxx I need to get 12 , if I have 50.xxx I want 51

Sorry The chunkSize should be int

How can I achieve this?

like image 523
Wearybands Avatar asked Apr 23 '14 14:04

Wearybands


3 Answers

Math.ceil() will do the work.

But, your assumption that 91 / 8 is 11.375 is wrong. In java, integer division returns the integer value of the division (11 in your case).

In order to get the float value, you need to cast (or add .0) to one of the arguments:

float chunkSize  = 91 / 8.0 ;
Math.ceil(chunkSize); // will return 12!
like image 87
BobTheBuilder Avatar answered Nov 18 '22 21:11

BobTheBuilder


ceil is supposed to do just that. I quote:

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.

EDIT: (thanks to Peter Lawrey): taking another look at your code you have another problem. You store the result of integer division in a float variable: float chunkSize = 91 / 8 ; java looks at the arguments of the division and as they are both integers it performs integer division thus the result is again an integer (the result of the division rounded down). Now even if you assign this to the float chunkSize it will still be an integer(missing the double part) and ceil, round and floor will all return the same value. To avoid that add a .0 to 91: float chunkSize = 91.0 / 8;. This makes one of the arguments double precision and thus double division will be performed, returning a double result.

like image 40
Ivaylo Strandjev Avatar answered Nov 18 '22 19:11

Ivaylo Strandjev


If you want to do integer division rounding up you can do

x / y rounded up, assuming x and y are positive

long div = (x + y - 1) / y;

In your case

(91 + 8 - 1) / 8 = 98 / 8 = 12

This works because you want to round up (add one) for every value except an exact multiple (which is why you add y - 1)

like image 8
Peter Lawrey Avatar answered Nov 18 '22 19:11

Peter Lawrey