Phillipp's avatar

Eloquent cast to float

hey,

I have a float(10,2) field in my table.

The value from the first row is 2.95 but eloquent gives me 3 as float.

Casting it to float or float(10,2) in the model have no effect.

Any ideas?

0 likes
10 replies
Phillipp's avatar
protected $casts = [
        'id' => 'integer',
        'shipping_free_over' => 'float',
        'shipping_fee_value' => 'float(10,2)',
        'shipping_min_order' => 'float',
        'view' => 'integer',
        'deducted_prescription' => 'float',
        'dif' => 'float',
        'contract' => 'integer',
        'reseller' => 'integer',
    ];

Both float and float(10,2) gives me rounded float numbers. 2.95 -> 3, 30.00 -> 30

2 likes
kazehaya's avatar

Why don't you try to store it as decimal in your database instead of float?

Phillipp's avatar

That's not my database. It's an existing database and I cannot edit the field types.

Phillipp's avatar

Thats not my problem. My problem is that eloquent gives me the rounded value but I need the unrounded value.

JarekTkaczyk's avatar

@Phillipp I meant the code you're executing. Anyway, I guess there's a problem with delimiter - Make sure both db value and php code use the same delimiter . or , - in php it may depend on locale settings.

Phillipp's avatar

The only thing I do is to return Model::first(). No other code yet.

simonhughes's avatar

2 years late to the party, but; having been caught out by this myself, I've looked at the source for HasAttribute.php where you can find the code for $casts. There you can see that Laravel purely (cast)s the value, you cannot use float(9,2) etc

https://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L462

To get the format you need, I suggest using accessors/mutators to perform a manual cast or number_format for those fields.

1 like
WizAmit's avatar

Use decimal:<digits>

protected $casts = [
     'shipping_fee_value' => 'decimal:2' 
]
4 likes

Please or to participate in this conversation.