Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct php typehint for doctrine column type "decimal"

I use this column in one of my entities:

/**
 * @var float
 * @ORM\Column(type="decimal", precision=20, scale=2)
 */
public $value;

According to the Doctrine docs, the decimal type is returned as a string to PHP, but I am using it as a float. Should I typehint it with @var float then, or is @var string correct?

Anyway, If I use this variable for arithmetic calcualtions, eg.

$object->value + $otherobject->value

am I risking to get undesired behaviour (like only adding the integer parts )?

like image 902
olidem Avatar asked May 16 '26 23:05

olidem


1 Answers

Generating an entity with the command line tools provided by Symfony 4, a field of type decimal can be generated like this:

New property name (press <return> to stop adding fields):
> percent

Field type (enter ? to see all types) [string]:
> decimal

Precision (total number of digits stored: 100.00 would be 5) [10]:
> 5

Scale (number of decimals to store: 100.00 would be 2) [0]:
> 4

This results into the following property and getter/setter methods:

<?php

// ...

/**
 * @ORM\Column(type="decimal", precision=5, scale=4)
 */
private $percent;

public function getPercent()
{
    return $this->percent;
}

public function setPercent($percent): self
{
    $this->percent = $percent;

    return $this;
}

So per default Doctrine generates the getter/setter methods without type hinting.
The getter will return string, while the setter expects an argument of type double (which is just a synonym for float).
Therefore you couldn't do something like:

/**
 * @var float
 */
private $value;

Since the value will be returned as string you shouldn't do calculations like the one in your question, but take care for previous transformation.

EDIT:
An alternative to type hinting with string or float can be the external library PHP decimal.

You can install it with this command:

composer require php-decimal/php-decimal
like image 132
cezar Avatar answered May 18 '26 15:05

cezar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!