views:

43

answers:

4

If I have 2 database records and 25 records per page, then the following code:

System.out.println("page count: " + (double)2/25);

results in this output:

page count: 0.08

But because I am using this figure for pagination, I need the next highest integer, in this case: 1.

Both Math.ceil and Math.abs produce the result 0 or 0.0.

How do I end up with a page number integer?

A: 

Once you get 0.08, add 0.5 then do Math.floor.

BoltBait
@Linc: you ALWAYS add 0.5 before using floor. Or, you could use Math.round which works like this: (int)Math.floor(a + 0.5f)
BoltBait
+1  A: 

You can add 1 to your result and then do a cast to int.

(int) (1 + (double)2/25)

This will go to the next higher number and then truncate.

James Black
+4  A: 

The correct way to do that is:

int pages = (totalRecords+recordsPerPage-1)/recordPerPage;

In your case: pages = (2 + 25 - 1)/25 = 26/25 = 1

Maurice Perry
+1: I can tell I'm used to dealing with PHP and the like... I thought about int / int equaling an int as to why `Math.ceil` wasn't working properly, but not for producing the correct result without using `ceil`/`floor`.
R. Bemrose
+1  A: 

Math.ceil should never give you 0 for 0.08. Clearly there's a bug in the code you didn't post.

System.out.println(Math.ceil((double)2/25));

outputs 1.0 in Java 6u21 just like you would expect.

At a guess, your other code is missing the cast to double on one of the arguments, and int / int always returns int in Java.

System.out.println(Math.ceil(2/25));

prints 0.0.

R. Bemrose
I was doing: Math.ceil((2/25))
Linc
@Linc: You need to cast `2` or `25` to a double first, or you get int `0` before doing `Math.ceil`. I've edited my answer to note that.
R. Bemrose