How can the Symfony Serializer Component be configured to normalize a float property of an object (entity)?
In detail: the taxRate property of a doctrine entity is is mapped to a PHP float value. And I would like to respond from a controller with a JSON representation like:
{taxRate:0.19}
But what I get is
{taxRate:"0.19"}
The definition of the entity's property and annotations are:
class ExampleEntity {
/**
* @ORM\Column(type="decimal", precision=3, scale=2, nullable=true)
* @Groups({"api"})
*/
protected $taxRate;
}
The controller looks like this:
$serializer = $this->get('serializer');
return new JsonResponse(
$serializer->normalize(
$exampleEntity,
'json',
[
'groups' => 'api',
]
)
);
I don't like the solution of converting the string into a Float on the JavaScript side. My app would like to assert the property is NULL or a Float value.
How can this be done?
Thanks to the comments, I think the question is not very clear/can be removed.
The serialization process is fine, it's the mapping from Doctrine which I did not get right.
It is totally OK, DECIMAL Doctrine/MySQL types are mapped to PHP strings. DECIMAL is designed to guarantee a precision for a numeric value. PHP's float type cannot guarantee the same precision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With