Maxime Pinot

Prevent a number to be rouned (scaled) in a Symfony form

In a Symfony form, if you expect your users to submit a decimal number, you will likely use a NumberType.

However, a NumberType always scale the submitted number (by default, 3 decimals are kept). This behaviour can be configured through the scale option. Yet, the scale option cannot be disabled, and you will not be able to prevent Symfony from rounding the submitted number.

To prevent Symfony from rounding the submitted number, you will need to use a TextType.

Be careful, though! Simply using a TextType will not be enough! You have to make sure that your users will submit a valid numeric string. To do so, you need to add a validation constraint. The constraint Type is what you need!

Here is the code to have a form field that only accepts a valid numeric string :

 5namespace Foo;
 7use Symfony\Component\Form\AbstractType;
 8use Symfony\Component\Form\Extension\Core\Type\TextType;
 9use Symfony\Component\Form\FormBuilderInterface;
10use Symfony\Component\Validator\Constraints\Type;
12final class FooType extends AbstractType
14    public function buildForm(FormBuilderInterface $builder, array $options)
15    {
16        $builder->add('numeric', TextType::class, [
17            'constraints' => new Type(['type' => 'numeric'])
18        ]);
19    }