Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal return string in Doctrine

I have a field Decimal like this

 /**
 *
 * @ORM\Column(name="foo", type="decimal", precision=0, scale=2, nullable=false, unique=false)
 */
private $foo;

When I use getFoo() or QueryBuilder my value is "159.79" instead of 159.79. How can I get the correct type?

like image 703
monkeyUser Avatar asked Nov 10 '16 15:11

monkeyUser


1 Answers

Even though you have declared it as a decimal in your Doctrine annotation, when it is retrived PHP will treat it as a string.
Reference here.

Values retrieved from the database are always converted to PHP’s string type or null if no data is present.

You could change the getter to cast as a float and then return.
E.g.

public function getFoo()
{
    return (float) $this->foo;
}

or

public function getFoo()
{
    return floatval($this->foo);
}

Look at Type Juggling for more info.
More info on floatVal() here

like image 157
Rooneyl Avatar answered Nov 15 '22 04:11

Rooneyl