Home / Rounding numbers with PHP

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.

echo round(153.751, 2);  // 153.75
echo round(153.751, 1);  // 153.8
echo round(153.751);     // 154
echo round(153.751, -1); // 150
echo round(153.751, -2); // 200

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.

echo ceil(153.251); // 154
echo ceil(153.751); // 154
echo ceil(-153.251); // -153
echo ceil(-153.751); // -153

floor()

The floor() functuon works the same was as ceil() but always rounding down to the nearest integer. Some examples:

echo floor(153.251); // 153
echo floor(153.751); // 153
echo floor(-153.251); // -154
echo floor(-153.751); // -154

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.

echo number_format(153.751); // 154
echo number_format(153.751, 1); // 153.8
echo number_format(153.751, 2); // 153.75

printf() and sprintf()

The printf() and sprintf() functions are also for formatting and again will round numbers as well. printf() outputs the value to standard output whereas sprintf() returns it as a value.

printf("%0.2f", 153.751); // 153.75
printf("%0.1f", 153.751); // 153.8
printf("%d", 153.751); // 153