基于用户输入的Do While循环拆分带小数的总时长至对应费率组
带小数时长的费率拆分问题
费率数组示例
[ [ 'rate_id' => 1, 'after' => 0, 'units' => 0, 'rate' => 0 ], [ 'rate_id' => 2, 'after' => 8, 'units' => 0, 'rate' => 12 ], [ 'rate_id' => 3, 'after' => 12, 'units' => 0, 'rate' => 15 ] ]
需求说明
after字段为加班费率生效阈值- 需要将带小数的总时长(如15.5小时)按费率规则拆分到对应组,例如15.5小时应拆分为:第一组8小时、第二组4小时、第三组3.5小时
当前实现代码(Laravel)
$totalTime = $item->units; $rates = $item->timesheet->rates() ->orderBy('after', 'desc') ->get() ->keyBy('after') ->map(function($item) { return [ 'units' => 0, 'rate_id' => $item['id'] ]; })->toArray(); do { foreach ($rates as $after => $rate) { if ($totalTime >= $after) { $rates[$after]['units'] = $rates[$after]['units'] + 1; break; } } $totalTime -= 1; } while ($totalTime >= 1); $rates = collect($rates)->filter(function ($item, $key) { return $item['units'] > 0; });
问题
当前代码仅能处理整数时长,处理带小数的总时长时精度异常;调整步长为0.1后仍无法正常运行,求解决方案。
内容的提问来源于stack exchange,提问作者Jonny
相关产品推荐
相关产品推荐

