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

Yii2新手求助:如何在GridView的harga字段使用number_format

Yii2 GridView中格式化'harga'字段为数字格式

你只需要把原来的'harga'字段定义改成数组形式,通过value回调函数调用number_format来格式化数值,同时可以处理空值避免报错:

<?= GridView::widget([
    'dataProvider' => $dataProvider, 
    'filterModel' => $searchModel,         
    'columns' => [             
        ['class' => 'yii\grid\SerialColumn'],             
        'kode',
        'uraian',
        'spek:ntext',
        'satuan',
        [
            'attribute' => 'harga',
            'value' => function ($model) {
                // 处理空值,默认显示0,按需调整
                return $model->harga ? number_format($model->harga, 0, ',', '.') : '0';
                // 若需保留2位小数,可改成:number_format($model->harga, 2, ',', '.')
            },
        ],
        // 其他列定义...
    ]
]); ?>

说明:

  • attribute指定字段名,保证字段对应的过滤器能正常工作
  • value是匿名函数,接收当前行的模型对象,返回格式化后的字符串
  • number_format的参数依次为:目标数值、小数位数、小数分隔符、千位分隔符,你可以根据地区习惯调整(比如中文环境可改为number_format($model->harga, 2, '.', ','))

如果harga字段是字符串类型,建议先转成数值再格式化:

'value' => function ($model) {
    $harga = (float)$model->harga;
    return $harga ? number_format($harga, 0, ',', '.') : '0';
},

内容的提问来源于stack exchange,提问作者farhan ayubi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:55:28