价格、点击量、库存、积分这些数字字段,直接输出往往是"1234567"这样的裸数字,可读性差。织梦模板里可以用 PHP 内置函数或自定义函数对数字进行千分位、小数位、单位换算等格式化。本文汇总常用写法。
一、number_format 千分位格式化
PHP 内置 number_format 是最常用的数字格式化函数:
// 基础用法 [field:click function="number_format(@me)"/] 输出:1,234,567 // 保留 2 位小数 [field:price function="number_format(@me,2)"/] 输出:1,234.56 // 指定小数点与千分位符号(人民币常用) [field:price function="number_format(@me,2,'.',',')"/] 输出:1,234.56
二、典型数字字段格式化
| 字段 | 原始值 | 格式化写法 | 输出 |
|---|---|---|---|
| click(点击量) | 1234567 | number_format(@me) | 1,234,567 |
| price(价格) | 1999.5 | number_format(@me,2) | 1,999.50 |
| stock(库存) | 12345 | number_format(@me) | 12,345 |
| scores(积分) | 9999 | number_format(@me) | 9,999 |
| weight(重量) | 1.5 | @me.' kg' | 1.5 kg |
| money(金额) | 8888 | '¥'.number_format(@me,2) | ¥8,888.00 |
三、价格字段格式化示例
1. 标准价格(2 位小数 + 货币符号)
<span class="price">
¥{dede:field.price function="number_format(@me,2)"/}
</span>
输出:¥1,999.50
2. 整数价格(去小数)
{dede:field.price function="number_format(@me,0)"/}
输出:1,999
3. 万元换算(大额商品)
[field:price runphp='yes']
if(@me >=10000){
@me=number_format(@me/10000, 2).' 万';
} else {
@me=number_format(@me, 2).' 元';
}
[/field:price]
输出:12,345 → 1.23 万
四、点击量智能格式化
大数字用"万"显示更易读:
function FormatClick($num){
if($num >=10000){
return number_format($num/10000, 1).'万';
}
return number_format($num);
}
[field:click function="FormatClick(@me)"/] 12345 → 1.2万 1234567 → 123.5万
五、库存状态显示
[field:stock runphp='yes']
if(@me==0){
@me='<span class="out">缺货</span>';
} elseif(@me < 10){
@me='<span class="low">仅剩 '.@me.' 件</span>';
} else {
@me='<span class="ok">库存 '.number_format(@me).' 件</span>';
}
[/field:stock]
六、评分星级显示
[field:scores runphp='yes']
$star=round(@me/20); // 假设满分 100,换算为 5 星
$html='';
for($i=1;$i<=5;$i++){
if($i<=$star) $html .='★';
else $html .='☆';
}
@me=$html.' ('.number_format(@me).')';
[/field:scores]
输出:★★★☆☆ (65)
七、百分比格式化
[field:discount runphp='yes'] @me=number_format(@me*100, 1).'%'; [/field:discount] 0.85 → 85.0%
八、文件大小格式化
function FormatSize($bytes){
if($bytes < 1024) return $bytes.' B';
if($bytes < 1048576) return number_format($bytes/1024, 1).' KB';
if($bytes < 1073741824) return number_format($bytes/1048576, 1).' MB';
return number_format($bytes/1073741824, 2).' GB';
}
调用:
[field:filesize function="FormatSize(@me)"/] 1234567 → 1.2 MB
九、注意事项
number_format 返回字符串:格式化后是字符串类型,不能再用作数学运算。如需计算后再显示,先计算后格式化。
价格字段注意类型:如果价格字段在数据库是 varchar 类型,number_format 前建议 floatval(@me) 转换,避免非数字字符串报错。
负数处理:number_format 对负数也能正常工作,如 -1234.5 会输出 -1,234.50。但自定义函数里的 if 判断要考虑负数场景(如退单金额)。
小数末尾去零:number_format(@me,2) 会强制补零(1999 → 1,999.00)。若想"整数不显小数、小数才显",用 rtrim(number_format(@me,2),'0.')。
十、应用建议
数字格式化的核心是"提升可读性":金额加千分位与货币符号、点击量超万转万显示、库存为 0 提示缺货、评分换算成星级。建议把 FormatClick、FormatSize、FormatPrice 等常用格式化函数集中放进 extend.func.php,全站统一调用,避免每个模板都写 runphp。电商类站点特别注意价格显示的一致性:全站价格统一用 number_format(@me,2) 保留 2 位小数,配合货币符号与红色样式,既专业又避免"1999"与"1999.00"混用的廉价感。把数字字段格式化做成模板规范,站点质感会明显提升。