The optional number of decimal digits to round to.
If the precision is positive, num is
rounded to precision significant digits after the decimal point.
If the precision is negative, num 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 num is rounded to tens,
for a precision of -2 to hundreds, etc.
mode
Use RoundingMode or one of the following constants to specify the mode in which rounding occurs.
Using PHP_ROUND_HALF_UP with 1 decimal digit precision
float(1.6)
float(-1.6)
Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision
float(1.5)
float(-1.5)
Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision
float(1.6)
float(-1.6)
Using PHP_ROUND_HALF_ODD with 1 decimal digit precision
float(1.5)
float(-1.5)
As PHP doesn't have a a native number truncate function, this is my solution - a function that can be usefull if you need truncate instead round a number.
<?php /** * Truncate a float number, example: <code>truncate(-1.49999, 2); // returns -1.49 * truncate(.49999, 3); // returns 0.499 * </code> * @param float $val Float number to be truncate * @param int f Number of precision * @return float */ function truncate($val, $f="0") { if(($p = strpos($val, '.')) !== false) { $val = floatval(substr($val, 0, $p + 1 + $f)); } return $val; } ?>
this function (as all mathematical operators) takes care of the setlocale setting, resulting in some weirdness when using the result where the english math notation is expected, as the printout of the result in a width: style attribute!
Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit.
round() will sometimes return E notation when rounding a float when the amount is small enough - see https://bugs.php.net/bug.php?id=44223 . Apparently it's a feature.
To work around this "feature" when converting to a string, surround your round statement with an sprintf: