How can I round an integer down to the nearest multiple of 3 using PHP? And have <3 be 0.
For example:
4 becomes 3
10 becomes 9
9 becomes 9
8 becomes 6
And so on...
How can I round an integer down to the nearest multiple of 3 using PHP? And have <3 be 0.
For example:
4 becomes 3
10 becomes 9
9 becomes 9
8 becomes 6
And so on...
Assuming $x
is your input:
print $x-$x%3;
Is this what you looking for.
/**
* Round an integer down to the nearest multiple of the given multiple
* @param integer $number
* @param integer $multiple
* @return integer
*/
function round_down_to_multiple_of( int $number, int $multiple = 3 ): int
{
return (int)($multiple * floor( $number/$multiple ));
}
# TESTS
$numbers = [ 10, 9, 8, 1, 0 ];
foreach( $numbers as $number ){
printf( '%d became %d'.PHP_EOL, $number, round_down_to_multiple_of( $number, 3 ) );
}
After running the above test I get the following results:
10 became 9
9 became 9
8 became 6
1 became 0
0 became 0
I misread that even if it is a perfect fit, it should round down to the last preceeding incremental:
4 becomes 3
10 becomes 9
9 becomes 6
8 becomes 6
Therefore, if for some reason you need this; your answer would be:
print $x-($x-1)%3-1;
I made a mistake in comprehending the question but thought this answer was curious enough to be worth posting.
If you want for 3, you may use function below:
function round_nearest_3($value){
return $value-$value%3;
}
If you want to return function for any value use function below:
function round_nearest_mod($value,$mod){
return $value-$value%$mod;
}
Examples:
echo round_nearest_3(4); // becomes 3
echo round_nearest_3(10); // becomes 9
echo round_nearest_3(9); // becomes 9
echo round_nearest_3(8); // becomes 6
echo round_nearest_mod(4,3); // becomes 3
echo round_nearest_mod(10,3); // becomes 9
echo round_nearest_mod(9,3); // becomes 9
echo round_nearest_mod(8,3); // becomes 6
<?php
//requested number
$num = 10;
//calc
for($i=1;($i*3)<=$num;$i++)$answer[] = $i;
$answer = max($answer)*3;
//print result
print_r($answer);