HowTo – Rounding Numbers With PHP round() Function

Filed under: Web Design

You will find that there are times when processing numbers or displaying results is better done with a rounded number then an exact one.  For instance if you were displaying the number of songs on your website or the number of hamburgers you have sold you may want to use a description such as 25,000 rather then 25,389…

To calculate a rounded number using PHP you use the round() function

The function will process the original number based on the places to the left of the decimal that you want to round. For instance

[php]
<?php
$num = 123456789;

echo round($num,0); // whole number – prints 123456789
echo round($num,-1); // ten – prints 123456790
echo round($num,-2); // hundred – prints 123456800
echo round($num,-3); // thousand – prints 123457000
echo round($num,-4); // ten thousand – prints 123460000
echo round($num,-5); // hundered thousand – prints 123500000
echo round($num,-6); // million – prints 123000000
echo round($num,-7); // ten million – prints 120000000
echo round($num,-8); // hundred million – prints 100000000
echo round($num,-9); // billion – prints 0
?>
[/php]

As you can see the negative number represents the number of places to the left of the decimal that you want to round to.

In addition to the number of places that you want to round to you can also set a variety of methods of rounding .. you can round up from 5 or down from 5 or only when odd or even.

[php]
<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9

echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9
?>
[/php]

If you need even more control over your rounded number results you can also see the related PHP functions:

ceil() – Round fractions up
floor() – Round fractions down
number_format() – Format a number with grouped thousands