2

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...

Martin
  • 22,212
  • 11
  • 70
  • 132
user3236406
  • 579
  • 1
  • 4
  • 10

6 Answers6

4

Assuming $x is your input:

print $x-$x%3;
man0v
  • 654
  • 3
  • 13
1

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
Kerkouch
  • 1,446
  • 10
  • 14
1

I know there are good answers here but this one is for larger numbers for the sake of alternative, using bcmath.

function floor_to_multiple($number, $multiplier) {
    return bcsub($number, bcmod($number, $multiplier));
}
Cemal
  • 1,469
  • 1
  • 12
  • 19
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.

Martin
  • 22,212
  • 11
  • 70
  • 132
0

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
MERT DOĞAN
  • 2,864
  • 26
  • 28
0
<?php
//requested number
$num = 10;
//calc
for($i=1;($i*3)<=$num;$i++)$answer[] = $i;
$answer = max($answer)*3;
//print result
print_r($answer);
Leo Tahk
  • 420
  • 1
  • 6
  • 15