开发者

Problem using Java's Math functions to come up with a page number for view pagination

开发者 https://www.devze.com 2023-01-16 11:51 出处:网络
If I have 2 database records and 25 records per page, then the following code: System.out.println(\"page count: \" + (double)2/25);

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 a开发者_运维知识库m 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?


The correct way to do that is:

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

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


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消