【问题标题】:Best way to round down in PHP在 PHP 中舍入的最佳方法
【发布时间】:2018-06-18 16:46:34
【问题描述】:

我有一个表格,当用户填写他们拥有的瓶子总数时,它会插入数据库,然后应该总结有多少个案例。

例如在葡萄酒中 - 有 12 个瓶箱,如果用户放入 100 瓶,则应将其除以 12 并得到 8.33333333 的总和。

$bottles = "100";

最好的方法是把它四舍五入到数字 8,然后计算出剩下多少瓶从未装满一箱?

希望这是有道理的。

【问题讨论】:

  • 尝试谷歌搜索php round down,字面意思是第一个结果php.net/manual/en/function.round.php
  • floor() 也是如此。是否进行过任何研究?
  • “向下取整的最佳方法”?您会拒绝非最佳方式的功能性和非功能性需求是什么?我很确定大多数四舍五入的方法都同样有效。

标签: php


【解决方案1】:

你可以使用floor

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

echo $case;

将导致 8

文档:http://php.net/manual/en/function.floor.php


如果你想检查剩下的瓶子,你可以使用模数

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

将导致 4

【讨论】:

  • OP 还问了and then work out how many bottles are left that never made it into a full case
  • @Sean,已更新。
  • 好奇:你给$bottles一个字符串值“100”有什么原因吗?
  • @RToyo 那是基于这个问题。给定的是字符串 100。
【解决方案2】:

您可以使用 floor 向下舍入,并使用模 (%) 运算符确定剩余的瓶子数量。

$bottles = 100;
$bottles_per_case = 12;

print "There are " . floor($bottles / $bottles_per_case) . " cases...";
print "With " . ($bottles % $bottles_per_case) . " bottles left over";

【讨论】:

    【解决方案3】:
    $bottles = "100";
    $case = (int) $bottles / 12 ;
    echo $case;
    $left = $bottles % 12;
    echo '<br>left: ' . $left;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      相关资源
      最近更新 更多