I want a php function which returns 55 when calling it with 52.
I've tried the round()
function:
echo round(94, -1); // 90
It returns 90 but I want 95.
Thanks.
I want a php function which returns 55 when calling it with 52.
I've tried the round()
function:
echo round(94, -1); // 90
It returns 90 but I want 95.
Thanks.
I know it's an old question, but IMHO using modulus operator is the best way, and far more elegant than the accepted answer.
Here is my version of Musthafa's function. This one is more complex but it has support for Float numbers as well as Integers. The number to be rounded can also be in a string.
I tried the functions from Knight, Musthafa and even the suggestion from Praesagus. They don't have support for Float numbers and the solutions from Musthafa's & Praesagus do not work correctly in some numbers. Try the following test numbers and do the comparison yourself:
Round down:
Round up:
Round to closest (up or down):
Multiply by 2, round to -1, divide by 2.
I do it like this:
Tests:
This can be accomplished in a number of ways, depending on your preferred rounding convention:
1. Round to the next multiple of 5, exclude the current number
Behaviour: 50 outputs 55, 52 outputs 55
2. Round to the nearest multiple of 5, include the current number
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 50
3. Round up to an integer, then to the nearest multiple of 5
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 55