Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Pagination, Math.Ceiling

Tags:

c#

.net

rounding

I'm creating some pagination and I'm getting an issue.

If I have a number 12 and I want to divide that by 5 (5 is the number of results I want on a page), how would I round it up properly? This doesn't work:

int total = 12;
int pages = Math.Ceiling(12 / 5);
//pages = 2.4... but I need it to be 3
like image 479
dcolumbus Avatar asked Dec 30 '10 22:12

dcolumbus


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

Even though your code should work, Math.Round is wrong though, you could try this:

int pages = (total + pageSize - 1)/pageSize;

That should be the same as Math.Ceiling except that you are always dealing with int and not double at any point as Math.Ceiling returns.

EDIT: To get your code to work you could try:

int pages = (int)Math.Ceiling((double)12/(double)5);

But you should use the first example.

like image 50
Tomas Jansson Avatar answered Sep 28 '22 06:09

Tomas Jansson


you could do:

int numPages = Math.Ceiling((decimal)12 / (decimal)5);

or

int numPages = (12 + 4) / 5;  //(total + (perPage - 1)) / perPage
like image 31
Chad Avatar answered Sep 28 '22 06:09

Chad