简体   繁体   English

Symfony2默认数字格式

[英]Symfony2 default number format

I want to change the default number format in a Symfony 2 project. 我想在Symfony 2项目中更改默认数字格式。

Instead of printing the numbers like 10.55 I want to display the decimal separator as a comma 10,55 . 我不想打印像10.55这样的数字,而是将小数点分隔符显示为逗号10,55

Not in the a Twig template but in all the forms. 不在Twig模板中,而是所有形式。 If I want to that is a Twig is as easy as use the number_format function . 如果我想要的是Twig,就像使用number_format函数一样容易。

I've already set my locale in the config.yml file. 我已经在config.yml文件中设置了语言环境。

You probably are using a number type field in your form type. 您可能在表单类型中使用了number类型字段。

So you could use the grouping option: 因此,您可以使用grouping选项:

[...] numbers will be grouped with a comma or period (depending on your locale): 12345.123 would display as 12,345.123. 号码将按逗号或句点分组(取决于您的语言环境):12345.123将显示为12,345.123。

Your code will look as following: 您的代码将如下所示:

// src/Acme/MyBundle/Form/Type/MyType.php
namespace Acme\MyBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class MyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('mynumber', 'number', array('grouping' => true));
    }

    public function getName()
    {
        return 'my';
    }
}

(you have the same option when using the money field type) (使用“ money字段类型时,您有相同的选择)

I also used the 'number' field type but one doesn't need the grouping option in the form type, from what I could test. 我还使用了“数字”字段类型,但是根据我的测试,不需要表单类型中的分组选项。 It is enough to render it in the twig template: see example below where {{ discount.discountRate }} is a float. 足以在树枝模板中呈现它:请参见下面的示例,其中{{ discount.discountRate }}是一个float。 If you replace it with '75.3869', you will find '75,39' 如果将其替换为“ 75.3869”,则会发现“ 75,39”

{# number with 2 decimal places, decimal comma, no thousands separator #}
{{ discount.discountRate|number_format(2, ',', '') }}%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM