Search code examples
yii2separatorphpword

Yii2: Format currency with thousands separator


I use PhpOffice\PhpWord for my Yii2 and Microsoft word 2016.

value data type decimal(15,2) when i download microsoftwordfile.docx from my project field value decimal show 10000.00 but i need 10,000.00 how to config/coding them to show 10,000.00

here myController.php

public function actionWord($id)
    {
     Settings::setTempDir(Yii::getAlias('@webroot').'/temp/');
     $templateProcessor = new TemplateProcessor(Yii::getAlias('@webroot').'/path/to/microsoftwordfile.docx');
     $model = Dataexample::findOne($id);
     $templateProcessor->setValue(
         [
            'amount',
         ],
         [
            $model->amount,
         ]);
         $templateProcessor->saveAs(Yii::getAlias('@webroot').'/path/to/microsoftwordfile.docx'); 
        echo Html::a('download', Url::to(Yii::getAlias('@web').'/path/to/microsoftwordfile.docx'), ['class' => 'btn btn-danger']);
     }

in microsoftwordfile.docx


Solution

  • Well you can use yii\i18n\Formatter to format the currency and it provides you the

    thousandSeparator : The character displayed as the thousands separator (also called grouping separator) character when formatting a number.

    Go to your common\config\main.php if you are using app-advanced or the app/config/main.php if app-basic nad add the following under components array.

    'formatter' => [
         'thousandSeparator' => ',',
         'currencyCode' => 'USD',
    ],
    

    Now you can format any given number like below

    Yii::$app->formatter->asCurrency(100.25);
    //will output 
    $100.25
    
    Yii::$app->formatter->asCurrency(1000.25);
    //will output
    $1,000.25
    
    Yii::$app->formatter->asCurrency(100000.25);
    //will output 
    $100,000.25
    

    You should change your function like below

    public function actionWord($id)
        {
         Settings::setTempDir(Yii::getAlias('@webroot').'/temp/');
         $templateProcessor = new TemplateProcessor(Yii::getAlias('@webroot').'/path/to/microsoftwordfile.docx');
         $model = Dataexample::findOne($id);
         $templateProcessor->setValue(
             [
                'amount',
             ],
             [
                Yii::$app->formatter->asCurrency($model->amount),
             ]);
             $templateProcessor->saveAs(Yii::getAlias('@webroot').'/path/to/microsoftwordfile.docx'); 
            echo Html::a('download', Url::to(Yii::getAlias('@web').'/path/to/microsoftwordfile.docx'), ['class' => 'btn btn-danger']);
         }
    

    Hope this helps.