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

Jul 20, 2020, 4:09:00 PM

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 :

<?php

declare(strict_types=1);

namespace Foo;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Type;

final class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('numeric', TextType::class, [
            'constraints' => new Type(['type' => 'numeric'])
        ]);
    }
}