I need to round the numbers.
46.38 >>> 46.40
46.40 >>> 46.40
46.41 >>> 46.50
I am using round($price, 1)
but this converts 46.41 to 46.40
. But i need 46.50
I need to round the numbers.
46.38 >>> 46.40
46.40 >>> 46.40
46.41 >>> 46.50
I am using round($price, 1)
but this converts 46.41 to 46.40
. But i need 46.50
You need ceil
instead of round, but it does not come with precision out of the box. You need to add this functionality yourself like e.g.
function myceil(int|float $number, int $precision, int $decimals) {
return number_format(ceil($number*(10**$precision))/(10**$precision), 2);
}
You can then use it as:
echo myceil(46.38,1, 2).PHP_EOL;
echo myceil(46.40,1, 2).PHP_EOL;
echo myceil(46.41,1, 2).PHP_EOL;
This will output:
46.40
46.40
46.50
Note: The number_format
is added to additionally control the decimals that will be shown in the end. It is not (strictly speaking) necessary and also causes the function output to be a string rather than a float.
I recommend this approach:
$roundedPrice = round($price + 0.05, 1, PHP_ROUND_HALF_DOWN);
This produces the outputs required from the inputs given.
... or more generally, if $precision
is the number of digits to the right of the decimal point,
$roundedPrice = round($price + (1/10**$precision)/2, $precision, PHP_ROUND_HALF_DOWN);