PHP百分比和不为1

比例和不为1

``````function ratio(\$nums, \$total)
{
\$ratio = \$nums ? bcdiv(\$nums, \$total, 4) : 0;
\$ratio_round = round(bcmul(\$ratio, 100, 2), 2);
return \$ratio_round;
}
\$result['order']['ratio']      = ratio(\$order_nums, \$total_nums);
\$result['order']['nums']       = number_format(\$order_nums, 0);
\$result['nopay']['ratio']      = ratio(\$nopay_nums, \$total_nums);
\$result['nopay']['nums']       = number_format(\$nopay_nums, 0);
\$result['cancel']['ratio']     = ratio(\$cancel_nums, \$total_nums);
\$result['cancel']['nums']      = number_format(\$cancel_nums, 0);
\$result['unpurchase']['ratio'] = ratio(\$unpurchase_nums, \$total_nums);
\$result['unpurchase']['nums']  = number_format(\$unpurchase_nums, 0);

``````

``````19.67333...  ≈  19.67
35.24333...  ≈  35.24
45.08333...  ≈  45.08
0            ≈  0

``````

蹩脚的解决方案

``````// 其中的某几次运行结果
19.67 + 35.24 + 45.09 + 0    = 100
19.67 + 35.25 + 45.08 + 0    = 100
19.68 + 35.24 + 45.08 + 0    = 100
19.67 + 35.24 + 45.08 + 0.01 = 100

``````

``````function ratio(\$nums, \$total)
{
\$ratio = \$nums ? bcdiv(\$nums, \$total, 4) : 0;
\$ratio_round = round(bcmul(\$ratio, 100, 2), 2);
return \$ratio_round;
}
\$result['order']['ratio']      = ratio(\$order_nums, \$total_nums);
\$result['order']['nums']       = number_format(\$order_nums, 0);
\$result['nopay']['ratio']      = ratio(\$nopay_nums, \$total_nums);
\$result['nopay']['nums']       = number_format(\$nopay_nums, 0);
\$result['cancel']['ratio']     = ratio(\$cancel_nums, \$total_nums);
\$result['cancel']['nums']      = number_format(\$cancel_nums, 0);
\$result['unpurchase']['ratio'] = ratio(\$unpurchase_nums, \$total_nums);
\$result['unpurchase']['nums']  = number_format(\$unpurchase_nums, 0);
// 比例已经获得，下面就是补充缺失的部分
// 首先先获取比例和
\$sum = 0;
array_walk(\$result, function (\$item) use (&\$sum) {
});
// 判断比例和是否已经满足条件，不满足则fix
if (bccomp(100, \$sum)) {
\$nums = array('order' => \$order_nums, 'nopay' => \$nopay_nums, 'cancel' => \$cancel_nums, 'unpurchase' => \$unpurchase_nums);
// 获取剩余的
\$rest = bcsub(100, \$sum, 2);
// 获取最大值的那个key
\$key = array_search(max(\$nums), \$nums);
// 加上剩余的值
}

``````

问题

``````24 -> 23.52
39 -> 38.25
39 -> 38.23
0  -> 0

``````

-- EOF --