I cannot seem to figure out how to always round up in PHP. ceil()
would be the obvious choice but I need the same functionality that round()
provides with its second parameter "precision". Here is an example:
// Desired result: 6250 echo round(6244.64, -2); // returns 6200 echo round(6244.64, -1); // returns 6240 echo ceil(6244.64) // returns 6245
I need the number to always round up so that I can calculate an equal divisor based on parameters for a chart.
Some of these answers have issues with floating point arithmetic which can fail as shown in this answer. For a bulletproof solution in all cases, use these:
From a comment on http://php.net/manual/en/function.ceil.php:
You could divide by 10, ceil(); and then multiply by ten
As version
ceil(pow(10, $precision) * $value) / pow(10, $precision);
fails in some cases, e.g. round_up(2.22, 2) gives incorrect 2.23 as mentioned here, so I have adapted this string solution for round_down() to our round_up() problem. This is the result (a negative precision is not covered):I don't know it is bulletproof, but at least it removes the above mentioned fail. I have done no binary-to-decimal-math-analysis but if
$floorValue + pow(10, 0 - $precision)
works always as expected then it should be ok. If you will find some failing case let me know - we should look for another solution :)One more solution for ceil with precision, no pow, it looks like works 9 digits both sides: