我们想将已经限制为至少 1、5、15、25、50、100 的整数四舍五入。这就是我想出的:
function roundDown($count) {
$prev = 1;
foreach ([5, 15, 25, 50, 100] as $limit) {
if ($count < $limit) {
return $prev;
}
$prev = $limit;
}
return 100;
}
它的工作,但我对此感觉不好。
function roundDown($count) {
foreach ([100, 50, 25, 15, 10, 5, 1] as $limit) {
if ($count >= $limit) {
return $limit;
}
}
return $limit;
}
感觉好些了吗?
这个:
return max(array_filter([100, 50, 25, 15, 5, 1], function ($x) use ($count) { return $x < $count; }) ?: [1]);
碰巧也可以工作,但它不是特别可读。