【问题标题】:Yii2: Format currency with thousands separatorYii2:用千位分隔符格式化货币
【发布时间】:2018-09-05 20:52:34
【问题描述】:

我的 Yii2 和 Microsoft word 2016 使用 PhpOffice\PhpWord

值数据类型decimal(15,2) 当我从我的项目字段值十进制显示10000.00 下载microsoftwordfile.docx 时,但我需要10,000.00 如何配置/编码它们以显示10,000.00

这里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']);
     }

【问题讨论】:

    标签: yii2 separator phpword


    【解决方案1】:

    您可以使用yii\i18n\Formatter 格式化货币,它为您提供

    thousandSeparator : 字符显示为千位 格式化时的分隔符(也称为分组分隔符) 号码。

    如果您使用的是app-advanced,请转到您的common\config\main.php;如果您使用的是app-basic,请转到app/config/main.php,然后在components 数组下添加以下内容。

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

    现在您可以像下面那样格式化任何给定的数字

    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
    

    你应该像下面这样改变你的功能

    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']);
         }
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢您,先生。你的解释很清楚,但我使用这个Yii::$app->formatter->asDecimal($model->amount, 2, [\NumberFormatter::MIN_FRACTION_DIGITS => 0]), 因为我不想显示符号货币代码。
    • 是的,如果你不打算显示货币符号,你可以使用asDecimal(),很乐意帮助@ChonjaroenChauynoo :)
    猜你喜欢
    • 2015-01-19
    • 2011-06-21
    • 2015-04-15
    • 2014-12-28
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 2022-07-31
    相关资源
    最近更新 更多