-5

I have a form, when a user fills in the total number of bottles they have, it inserts into a database and then should sum up how many cases there are.

For example in wine - there are 12 bottle cases, if a user puts in 100 bottles, it should divide this by 12 and give the sum of 8.33333333.

$bottles = "100";

What is the best way to round this down to just the number 8 and then work out how many bottles are left that never made it into a full case?

Hope this makes sense.

  • 5
    Try googling `php round down`, literally the first result http://php.net/manual/en/function.round.php. – MCMXCII Jan 09 '18 at 15:43
  • 5
    `floor()` as well. Was any research done? – IncredibleHat Jan 09 '18 at 15:44
  • 1
    "best way to round down"? What are your functional and non-functional requirements with which you would reject non-best ways? I'm pretty sure most ways to round down would work equally well. – apokryfos Jan 09 '18 at 15:44

3 Answers3

6

You can use floor

$bottles = "100";
$case = floor( $bottles / 12 );

echo $case;

Will result to 8

Documentation: http://php.net/manual/en/function.floor.php


If you want to check the bottles left, you can use modulo

$bottles = "100";
$left = $bottles % 12;

Will result to 4

Eddie
  • 26,593
  • 6
  • 36
  • 58
2

You can use floor to round down, and the modulo (%) operator to determine how many bottles are left.

$bottles = 100;
$bottles_per_case = 12;

print "There are " . floor($bottles / $bottles_per_case) . " cases...";
print "With " . ($bottles % $bottles_per_case) . " bottles left over";
RToyo
  • 2,877
  • 1
  • 15
  • 22
0
$bottles = "100";
$case = (int) $bottles / 12 ;
echo $case;
$left = $bottles % 12;
echo '<br>left: ' . $left;
Alam Darji
  • 275
  • 3
  • 13