format_number

这个 format_number 筛选设置数字格式:

1
{{ '12.345'|format_number }}

可以传递属性以调整输出:

1
2
3
4
5
{# 12.34 #}
{{ '12.345'|format_number({rounding_mode: 'floor'}) }}

{# 1000000.0000 #}
{{ '1000000'|format_number({fraction_digit: 4}) }}

支持的选项列表:

  • grouping_used
  • decimal_always_shown
  • max_integer_digit
  • min_integer_digit
  • integer_digit
  • max_fraction_digit
  • min_fraction_digit
  • fraction_digit
  • multiplier
  • grouping_size
  • rounding_mode
  • rounding_increment
  • format_width
  • padding_position
  • secondary_grouping_size
  • significant_digits_used
  • min_significant_digits_used
  • max_significant_digits_used
  • lenient_parse.

除了普通数字外,过滤器还可以格式化各种样式的数字:

1
2
3
4
5
6
7
8
{# 1,234% #}
{{ '12.345'|format_number(style='percent') }}

{# twelve point three four five #}
{{ '12.345'|format_number(style='spellout') }}

{# 12 sec. #}
{{ '12'|format_duration_number }}

支持的样式列表:

  • decimal
  • currency
  • percent
  • scientific
  • spellout
  • ordinal
  • duration .

作为快捷方式,可以使用 format_*_number 更换过滤器 * 风格:

1
2
3
4
5
{# 1,234% #}
{{ '12.345'|format_percent_number }}

{# twelve point three four five #}
{{ '12.345'|format_spellout_number }}

可以传递属性以调整输出:

1
2
{# 12.3% #}
{{ '0.12345'|format_percent_number({rounding_mode: 'floor', fraction_digit: 1}) }}

默认情况下,筛选器使用当前区域设置。可以显式传递:

1
2
{# 12,345 #}
{{ '12.345'|format_number(locale='fr') }}

注解

这个 format_number 过滤器是 IntlExtension 默认情况下不安装。先安装:

1
$ composer require twig/intl-extra

然后,在symfony项目上,安装 twig/extra-bundle

1
$ composer require twig/extra-bundle

否则,请在Twig环境中显式添加扩展::

use Twig\Extra\Intl\IntlExtension;

$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());

争论

  • locale :区域设置
  • attrs :属性映射
  • style :数字输出的样式