Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: Number format

Tags:

php

yii2

I have defined a column in Database as float. The column is being shown as number in the model. I want to format the columnn in Gridview with two decimal places and couldn't find a way, how it can be done.

I have tried to use this code but getting the error like - Unknown format type: number

[
   'label' => 'Charges',
   'attribute' => 'category_charges',
   'contentOptions' => ['class' => 'col-lg-1'],
   'format' => ['number',2] 
],

Thanks.

like image 771
Pawan Avatar asked Nov 22 '14 13:11

Pawan


2 Answers

Set grid column like this

'columns' => [
        [
            'format' => 'Currency',
            'attribute' => 'amount',
        ],            
    ],

in main.php add under 'components':

'formatter' => [
        'class' => 'yii\i18n\formatter',
        'thousandSeparator' => ',',
        'decimalSeparator' => '.',
        'currencyCode' => '$'
    ],
like image 93
jantbarco Avatar answered Sep 28 '22 03:09

jantbarco


The correct syntax of formatting decimal number is like below:

'format'=>['decimal',2]

So your code should be:

[
    'label' => 'Charges',
    'attribute' =>'category_charges',
    'contentOptions' => ['class' => 'col-lg-1'],
    'format'=>['decimal',2]
],

To be more familiar with Yii2's formatting take a look at the official document:

Class yii\i18n\Formatter

like image 43
Ali MasudianPour Avatar answered Sep 28 '22 04:09

Ali MasudianPour