Round Numbers to Next Whole Number in PHP

Time for a new php function, ceil().

A client needed to record the hours spent in particular activities by each member. The number of hours spent in assigned activities were to be entered in whole numbers, where partial hours were rounded up to the nearest hour. So, if someone spent an hour and twenty minutes on a particular activity they were to enter 2 hours into the web site form. However, as we all know, directions are not always read, so don’t trust your input.

Validate all database input!

What was the computer going to spit out on the reports when a person entered 1.3 instead of 2? Naturally the output was rounded down to 1 hour instead of up to 2 hours.

To round up all fractional numbers php has a function that allows us to round all fractions up to the next highest whole number: ceil(argument);

Use it like so:

ceil(5.34) produces the value 6, while ceil(5.56) also gives us 6.

You can throw a variable in the parentheses instead of decimals:

$time_spent = ceil($hours);

Using ceil() allowed me to format the data before it was inserted into the database. Now, reports of member activities will indicate the appropriate time spent.

Leave a Reply

Your email address will not be published. Required fields are marked *