@Phillipp Show the code
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?
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
Why don't you try to store it as decimal in your database instead of float?
That's not my database. It's an existing database and I cannot edit the field types.
hmm maybe the round function of php can help here?
Thats not my problem. My problem is that eloquent gives me the rounded value but I need the unrounded value.
@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.
The only thing I do is to return Model::first(). No other code yet.
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
To get the format you need, I suggest using accessors/mutators to perform a manual cast or number_format for those fields.
Use decimal:<digits>
protected $casts = [
'shipping_fee_value' => 'decimal:2'
]
Please or to participate in this conversation.