You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 19:35:53