Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round integer to nearest multiple of 5 in PHP

Tags:

php

rounding

Searching for a function ro round numbers to the nearest multiple of 5

22 -> 20
23 -> 25
40 -> 40
46 -> 45
48 -> 50

and so on.

Tried this which always returns the higher value:

5 * ceil($n / 5);
like image 924
Chris Avatar asked Oct 16 '12 11:10

Chris


People also ask

How do you round a number to the nearest 5 in PHP?

Rounding to the Nearest 5 degrees PHP's round() function takes a decimal number (a.k.a. floating point number) and rounds up or down. In its most simple and default form, it will round the decimal to the nearest whole number. For example, round(3.457) will give you the result 3 .

How do you round to the nearest multiple of 5?

If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.

How do you round an integer in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.

How do you round to the nearest multiple?

You can use CEILING to round prices, times, instrument readings or any other numeric value. CEILING rounds up using the multiple supplied. You can use the MROUND function to round to the nearest multiple and the FLOOR function to round down to a multiple.


1 Answers

Use round() instead of ceil().

5 * round($n / 5);

ceil() rounds a floating point number up to its next integer in sequence. round() will round to the nearest integer using standard rounding rules.

like image 163
alex Avatar answered Oct 05 '22 02:10

alex