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 :

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