yii2 - how to set currency decimal value

有些话、适合烂在心里 提交于 2019-12-21 16:17:11

问题


I want my currency to ignore decimal value, so far I have this:

main.php:

'formatter' => [
   'class' => 'yii\i18n\Formatter',
   'thousandSeparator' => '.',
   'decimalSeparator' => ',',
   'currencyCode' => '€',

],

view:

[
   'attribute' => 'Score',
   'format' => 'currency',
],

Any idea on how to move forward?


回答1:


The manual on currencyCode:

The 3-letter ISO 4217 currency code indicating the default currency to use

Try setting currencyCode to 'EUR' (though that doesn't seem to be that important) and put the formatter in an array

[
   'attribute' => 'Score',
   'format' => [
       'currency',
       'EUR',
       [
           \NumberFormatter::MIN_FRACTION_DIGITS => 0,
           \NumberFormatter::MAX_FRACTION_DIGITS => 0,
       ]
    ],
],

This requires the PHP intl extension to be installed. Status of the extension can be tested by calling extension_loaded('intl'). In absence of the extension, your best bet is probably to write a custom formatter.

<?php
namespace app\components;

class Formatter extends \yii\i18n\Formatter
{
    public function asRoundedCurrency($value, $currency)
    {
        return $this->asInteger(round($value)) . ' ' . $currency;
    }
}

Use it instead of the default formatter an then call it like this:

[
    'attribute' => 'Score',
    'format' => ['roundedCurrency', 'EUR'],
]

This also allows you to freely set the currency symbol.




回答2:


In main.php:

'formatter' => [
   'class' => 'yii\i18n\Formatter',
   'locale' => 'yourLocale', //ej. 'es-ES'
   'thousandSeparator' => '.',
   'decimalSeparator' => ',',
   'currencyCode' => 'EUR',

],

Be sure that php_intl extensions is installed. It works for me.

Link to the documentation yii-i18n-formatter.



来源:https://stackoverflow.com/questions/31742656/yii2-how-to-set-currency-decimal-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!