Rounding numbers with PHP

I have previously looked at rounding numbers with MySQL and Javascript and in this post look at rounding numbers with PHP using the round() ceil() floor() number_format() and s/printf() functions.

round()

The round() function rounds the number passed in to the specified number of decimal places. If the decimal places is a negative number then the numbers to the left of the decimal place are rounded. If the decimal places parameter is not passed in then it defaults to zero and will round as an integer. 5 is round up and < 5 is rounded down.

From PHP 5.3.0 round() accepts a 3rd parameter can be passed which specifys the rounding mode and is one of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD. It defaults to PHP_ROUND_HALF_UP to maintain backward compatibility.

ceil()

The ceil() function rounds up to the nearest integer (ceil = ceiling). There is no argument for precision so it will always round up to the nearest integer. If the number is already an integer then the value returned will remain the same.

number_format()

The PHP number_format() function is used for formatting numbers with decimal places and thousands separators, but it also rounds numbers if there are more decimal places in the original number than required. As with round() it will round up on 5 and down on < 5.