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

Smarty PHP中如何将1000等运算数值转换为1k、1.3k精简格式

实现数值转精简计数格式的三种方案

你当前使用的是Smarty模板的{math}标签,可通过以下三种方式实现1300转1.3k、1230000转1.2M这类量级转换效果:


方案1:自定义Smarty修饰器(推荐,模板层复用性最高)

先在Smarty插件目录或项目公共函数文件中新增自定义修饰器:

function smarty_modifier_compact_num($num, $decimals = 1) {
    $units = ['', 'k', 'M', 'G', 'T', 'P'];
    $unitIndex = 0;
    // 按千进制递进匹配量级
    while ($num >= 1000 && $unitIndex < count($units) - 1) {
        $num /= 1000;
        $unitIndex++;
    }
    return number_format($num, $decimals) . $units[$unitIndex];
}

模板层直接调用修饰器即可,修改原代码为:

<div>{math equation="x - y" x=$n.total_rating y=$n.total_ratings|compact_num}</div>
<!-- 如需保留2位小数可传参:|compact_num:2 -->

方案2:后端提前计算转换(性能最优)

如果不想修改Smarty配置,可在PHP赋值给模板前完成转换:

// 先计算差值
$diff = $n['total_rating'] - $n['total_ratings'];
// 转换为精简格式
$units = ['', 'k', 'M', 'G', 'T', 'P'];
$unitIndex = 0;
while ($diff >= 1000 && $unitIndex < count($units) - 1) {
    $diff /= 1000;
    $unitIndex++;
}
$n['compact_diff'] = number_format($diff, 1) . $units[$unitIndex];

模板层直接输出转换后的变量即可:

<div>{$n.compact_diff}</div>

方案3:前端JS处理(适合不想修改后端代码的场景)

给输出标签加专属类名,用JS批量转换数值:
模板原代码修改为:

<div class="compact-num">{math equation="x - y" x=$n.total_rating y=$n.total_ratings}</div>

页尾加入JS逻辑:

document.querySelectorAll('.compact-num').forEach(item => {
    let num = parseInt(item.textContent.trim());
    if (isNaN(num)) return;
    const units = ['', 'k', 'M', 'G', 'T', 'P'];
    let unitIndex = 0;
    while (num >= 1000 && unitIndex < units.length - 1) {
        num /= 1000;
        unitIndex++;
    }
    item.textContent = num.toFixed(1) + units[unitIndex];
})

内容的提问来源于stack exchange,提问作者Jarosław Król

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:30:04