In PHP I want to round numbers based on the value provided.
- If the value is more than 30, I want to round numbers to the closest 4.95 or 9.95
- If the value is between 10 and 30 I want to round numbers to the closest 2.45 or 4.95 or 7.45 or 9.95
- If the value is less than 10 I want to round numbers to the closest .45 or .95
- If the value is less than 1 I want to round numbers to the closest .05 or .10
The value however cannot be 0 or below zero and always round upwards when it’s close to zero (so it doesn’t become zero but 0.05 for example).
I have this code for rounding to the closest 4.95 or 9.95:
(ROUND($number / 5, 0) * 5) - 0.05
I have this code for rounding to the closest .45 or .95:
(ROUND($number * 2, 0) / 2) - 0.05
I don’t really know how to achieve the above though. Does anyone have an idea about it?
Advertisement
Answer
If I understand well your problem, this solution should work :
if ($value > 30) $roudedValue = 5 * round($value / 5); else if ($value >= 10) $roudedValue = 2.5 * round($value / 2.5); else if ($value > 1) $roudedValue = 0.5 * round($value / 0.5); else $roudedValue = 0.1 * round($value / 0.1);