Rounding Numbers in PHP
In PHP, the rounding of numbers
is done using the round function.
See an example of rounding to integers:
<?php
echo round(3.4); // will output 3
echo round(3.5); // will output 3
echo round(3.6); // will output 4
?>
The second parameter of the function can specify the number of digits in the fractional part. Let's round to tenths and hundredths:
<?php
echo round(3.345, 1); // will output 3.3
echo round(3.345, 2); // will output 3.35
?>
You can also round a number upwards.
For this, the ceil function is used.
See the example:
<?php
echo ceil(3.1); // will output 4
echo ceil(3.5); // will output 4
echo ceil(3.6); // will output 4
?>
You can also round a number downwards.
For this, the floor function is used.
See the example:
<?php
echo floor(3.9); // will output 3
echo floor(3.5); // will output 3
echo floor(3.1); // will output 3
?>