PHP round & ceiling not correctly parsing data
Pregunta
The numbers that are being pulled from an xml file and then assigned to a variable but are outputted incorrectly. I'm not quite sure why or how to get around it. An example is this.
$pricing_high = 1.15;
echo $pricing_high;
This displays 1.15 obviously. But when I assign this like so:
$price = ceil($pricing_high / 0.05) * 0.05;
echo $price;
This displays 2.
$price = round($pricing_high / 0.05) * 0.05;
echo $price;
This displays 1.
How do I get numbers to correctly round up to the nearest 5 cents when passing it like this?
Solución
As of PHP documentation for round function:
http://php.net/manual/en/function.round.php
You can specify precision as second parameter:
$pricing_high = 1.15;
$price = round($pricing_high / 0.05, 2) * 0.05;
echo $price;
Note value of second parameter 2
Otros consejos
Is 1.15
= 1 dollar and 15 cents? If so:
echo sprintf('%.2f', round($price / 0.05) * 0.05); // Rounds to nearest
echo sprintf('%.2f', ceil($price / 0.05) * 0.05); // Rounds up
Tests:
$price = 1.13;
echo sprintf('%.2f', round($price / 0.05) * 0.05); // Outputs: 1.15
echo sprintf('%.2f', ceil($price / 0.05) * 0.05); // Outputs: 1.15
$price = 1.12;
echo sprintf('%.2f', round($price / 0.05) * 0.05); // Outputs: 1.10
echo sprintf('%.2f', ceil($price / 0.05) * 0.05); // Outputs: 1.15
If 1.15
= 1.15 cents then replace 0.05
with 5
.
As ceil() and floor() don't have this precision, you might multiply your results and divide it after.