Home » Php » php – Rounding number to nearest interval

php – Rounding number to nearest interval

Posted by: admin July 12, 2020 Leave a comment

Questions:

So i have a predefined interval, can be 5, 10, 15, etc

If someone inputs 20 i need it to round up based on the interval. So if it was a 15 minute interval, it would automatically go to 30, if it was a 45 minute interval, it would go to 45

Basically anything <= interval becomes interval
anything inbetween intervals becomes the next highest interval

I dont want to write some convoluted php function to do this when there may be a simple way i am just not aware of.

How to&Answers:

Rounding up would be:

$ceiled = $interval * ceil( $value / $interval);

Answer:

roundedInput  = (Ceiling( Input / Interval)) * Interval

So, given an input of 20 and an interval of 15, you’d get:

20/15 = 1.33

1.33 rounded up = 2

2 * 15 = 30

Answer:

$Rounded = Ceil($value / $interval) * $interval;