0

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?

2
  • It sounds like the error is in code you're not showing us.
    – Powerlord
    Sep 15, 2010 at 15:43
  • Why do you say that? Is there something wrong with what I have written above? Could you explain what you mean?
    – Linc
    Sep 15, 2010 at 15:44

4 Answers 4

10

The correct way to do that is:

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

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

1
  • +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.
    – Powerlord
    Sep 15, 2010 at 15:55
5

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.

3
  • I was doing: Math.ceil((2/25))
    – Linc
    Sep 15, 2010 at 15:49
  • 1
    @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.
    – Powerlord
    Sep 15, 2010 at 15:51
  • @Linc Math.ceil((double)2/25) . I am sure this will work for you. Mar 5, 2020 at 7:58
2

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.

But, the correct equation would be:

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

So, if you have 25 then it would be:

0.5 + 25/25 

or

0.5 + 1 so int of that is 1

You can round up by adding .5 and taking the int.

1
  • This is wrong, imagine if there is 25 records, with pageSize=25. The formula gives 2 pages, even though there is only 1 page.
    – lipeiran
    May 3, 2017 at 22:24
0

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

1
  • @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
    Sep 15, 2010 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.