Pergunta

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?

Foi útil?

Solução

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!

Outras dicas

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.

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)

Firstly, when you write float chunkSize = 91 / 8 ; it will print 11.0 instead of 11.375

because both 91 and 8 are int type values. For the result to be decimal value, either dividend or divisor

or both have to be decimal value type. So, float chunkSize = 91.0 / 8; will result 11.375 and

now you can apply Math.ceil() to get the upper value. Math.ceil(chunkSize); will result in 12.0

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top