To round a number in PHP you can use one of three functions, these are round(), ceil() and floor(). All of these functions take number as the input and will round the value depending on the function used.
To round to the closest integer use the round() function.
round(4.4); // returns 4
To round down to the nearest whole number use the floor() function.
floor(4.4); // returns 4
To round up to the nearest whole number use the ceil() function.
ceil(4.4); // returns 5
Note that due to the way in which numbers are stored in PHP you can get inconsistent results from rounding a value like 4.5. This is because of the way in which they are stored on the computer. A value of 4.5 might have an actual value of 4.4999999999999999999999 or 4.5000000000000000000001 so when you try to round this value you might get 4 or 5.
To get around this you can add a tiny value to the number before you round it to act as a buffer.
round(4.5 + 0.0000001); // returns 5
The round() function also accepts a second parameter which allows you to set the number of decimal places to round to. In this case round() will round to the nearest significant digit.
round(4.51234,2); // returns 4.51
If you just want to print off the value rather than round it you can use a number of functions to help you do this. The simplest function to use is number_format() which will also add in thousand separators. number_format() takes 4 parameters, but only the first one (the number) is manditory.
number_format(123456.1234); // returns 123,456
The other parameters are
- decimals - The number of decimal places to round the value to
- Decimal point - The string to be used as the decimal point.
- Thousand Separator - The string to be used as a thousands separator.
echo number_format(123456.123456,2,'POINT','COMMA'); // prints 123COMMA456POINT12
Slightly more complicated is the money_format() function which takes two parameters, the number format and the value. This function is effected by the value set in the LC_MONETARY category of the locale settings. Set this value by using setlocale() before running the function. For more information on the format string see the PHP website.
setlocale(LC_MONETARY, 'en_GB'); $formatString = '%i (after 17.5%% tax)'; echo money_format($formatString, 1234.12) . "\n"; // prints GBP 1,234.12 (after 17.5% tax)
Lastly, you can also use the sprintf() function to format the string and return the output.
echo sprintf("%.2f",123.11); // prints 123.10