我在 Twig 中渲染货币价值,如下所示:
{{ amount | format_currency('EUR', {fraction_digit: 2, decimal_always_shown: false}, 'fr-FR') }}
如果
amount
没有小数,我想渲染它而不带小数位(例如:12
);
如果它有一些小数,我想精确地用 2 个小数位来渲染它(例如:12.10
和 12.23
)。
尝试一些参数组合(如上面的),值
12.10
被渲染为12.1
,而我想渲染12.10
。
有没有办法使用这里的参数来做到这一点https://twig.symfony.com/doc/3.x/filters/format_currency.html。参数似乎与
NumberFormatter
相同(https://www.php.net/manual/en/class.numberformatter.php#numberformatter.constants.lenient-parse)。
您必须首先测试该值,看看它是否有小数值,并使用适当的参数进行条件格式化。
{% if amount|round(2, 'common') == amount|round(0, 'floor') %}
{{ amount | format_currency('EUR', {fraction_digit: 0}, 'fr-FR') }}
{% else %}
{{ amount | format_currency('EUR', {fraction_digit: 2}, 'fr-FR') }}
{% endif %}
或者在格式化之前有条件地设置参数值。
{% set deci = (amount|round(2, 'common') == amount|round(0, 'floor')) ? 0 : 2 %}
{{ amount | format_currency('EUR', {fraction_digit: deci}, 'fr-FR') }}
或者你可以直接内联三元:
{{ amount | format_currency('EUR', {fraction_digit: (amount|round(2, 'common') == amount|round(0, 'floor')) ? 0 : 2}, 'fr-FR') }}