Blagoh
Blagoh

Reputation: 1235

Cast $casts to float but only one decimal place

In my model I added $casts field because I need Laravel to give me a float. My database is storing it as a string.

So I did this in my model Score.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Score extends Model
{
    protected $fillable = [
        'value', 'comment'
    ];

    protected $casts = [
        'user_id' => 'int',
        'value' => 'float'
    ];

This is great, it casts it. However it is going wayyyy too many decimal places. I need it to go only 1 decimal place, to the tenths.

My json endpoint data looks like this:

{
    "id": 2,
    "name": "Zed",
    "avatar_path": null,
    "score": {
        "id": 2,
        "value": 9.9000000000000003552713678800500929355621337890625,
        "comment": null,
        "user_id": 2,
        "created_at": "2018-05-03 07:03:37",
        "updated_at": "2018-05-03 07:03:41"
    }
},

I want that 9.9...... to just be 9.9 is this possible?

In my schema, I did i do it right to create it as $table->decimal('value', 3, 1):

    Schema::create('scores', function (Blueprint $table) {
        $table->increments('id');
        $table->decimal('value', 3, 1)->nullable(); //////// is this correct?

Upvotes: 0

Views: 6798

Answers (1)

zedling
zedling

Reputation: 637

How about creating a mutator/accessor?

In your model add

public function getValueAttribute($value) {
    return round($value, 1);
}

for extra info visit the related Laravel docs

If you are 100% sure you only need one decimal place, than the database approach is good too, but this way you can store the raw value for future use, and still respond with the currently desired format

Upvotes: 2

Related Questions