PHP [Versions: 4, 5, 7]
Returns the rounded value of a decimal number to the specified precision (number of digits after the decimal point). The specified precision may also be a negative or a zero.
- value (integer) (Required): The value you wish to round.
- precision (integer) (Optional) (Default = 0): The number of decimal places you’d like to round to.
- mode (integer) (Optional): (Default = PHP_ROUND_HALF_UP)
Other values for mode may be one of the following constants:
- PHP_ROUND_HALF_UP: Rounds value away from zero when it is half way there, making 1.5 into 2 and -1.5 into -2.
- PHP_ROUND_HALF_DOWN: Rounds value towards zero when it is half way there, making 1.5 into 1 and -1.5 into -1.
- PHP_ROUND_HALF_EVEN: Rounds value towards the nearest even value when it is half way there, making both 1.5 and 2.5 into 2.
- PHP_ROUND_HALF_ODD: Rounds value towards the nearest odd value when it is half way there, making 1.5 into 1 and and 2.5 into 3.
Return Value(s)Returns the rounded number to the specified precision.
If the precision is positive, the value is rounded to precision significant digits after the decimal point.
If the precision is negative, the value is rounded to precision significant digits before the decimal point, i.e. to the nearest multiple of pow(10, -precision), e.g. for a precision of -1 val is rounded to tens, for a precision of -2 to hundreds, etc.
Examples of round()
<?php $round = round(2.1234); print_r($round) // Output = 2
The above output will be 2.
<?php $round = round(2.1234, 2); print_r($round) // Output = 2.12
In this example, the second parameter is 2, meaning round to two decimal places. So the above output will be 2.12.
<?php $round = round(2.5, 0, PHP_ROUND_HALF_DOWN); print_r($round) // Output = 2
By default, round() will round up values of 0.5. You may override this by adding the PHP_ROUND_HALF_DOWN constant as the precision parameter. So the above will output 2 instead of 3.
<?php $round = round(68.7654); print_r($round) // Output = 69
The above will output 69.
Similar Functions in Other Languages