如何为PHP代码中的number_format添加数量判断条件?
PHP代码修改:根据数量值动态格式化数字
原代码如下:
$metMessage = ""; foreach($batches as $batch) { $metMessage .= '<tr> <td>' . $batch['comp_code'] . '</td> <td>' . $batch['description'] . '</td> <td>' . number_format($batch['quantity'], 0, '.', '') .'</td> </tr>'; }
需求:当$batch['quantity']小于3时,保留两位小数格式化;否则保留0位小数格式化。
修改后的代码:
$metMessage = ""; foreach($batches as $batch) { // 根据quantity的值选择格式化方式 $formattedQuantity = $batch['quantity'] < 3 ? number_format($batch['quantity'], 2, '.', '') : number_format($batch['quantity'], 0, '.', ''); $metMessage .= '<tr> <td>' . $batch['comp_code'] . '</td> <td>' . $batch['description'] . '</td> <td>' . $formattedQuantity .'</td> </tr>'; }
补充说明
如果觉得三元运算符不够直观,也可以使用常规的if-else语句实现相同逻辑:
$formattedQuantity = ''; if ($batch['quantity'] < 3) { $formattedQuantity = number_format($batch['quantity'], 2, '.', ''); } else { $formattedQuantity = number_format($batch['quantity'], 0, '.', ''); }
内容的提问来源于stack exchange,提问作者user21024361
相关产品推荐
相关产品推荐

