As3ad's avatar
Level 1

Problem when using number_format() function with Model Attribute accessor

Hello, I have an Invoice model with a total_amount attribute, I want to format the value and used

 public function totalAmount(): Attribute
    {
        return new Attribute(
            get: fn ($value) => number_format((float)$value, 2, '.', ','),
        );
    }

the problem is if value = 3047.00, the result showing is = 3.00. also if I tried number_format($value) without using the (float) before it, I get error: number_format(): Argument #1 ($num) must be of type float, string given

0 likes
10 replies
Amaury's avatar

@as3admystery did you try?

 public function totalAmount(): Attribute
    {
        return new Attribute(
            get: fn ($value) => number_format(floatval($value), 2),
        );
    }
As3ad's avatar
Level 1

@Amaury yes, and also still the same result. I'm using laravel 9 and php v8.2 if that would help

Amaury's avatar

@As3adMystery I was focused on the float part… In your model, what is the attribute you want to change?

As3ad's avatar
Level 1

@Amaury total_amount, also the database column is total_amount. the problem is it's like if the number is above a thousand, it deletes the first three digits. for example if the $value is 9055.00, it became 9.00 with number_format function. but if the value is 170.00 it stays the same.

Amaury's avatar

@As3adMystery And this?

protected function totalAmount(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => number_format(floatval($value), 2),
        );
    }
Amaury's avatar
Amaury
Best Answer
Level 43

@As3adMystery did you try with a method?

public function totalAmountFormatted()
{
    return number_format(floatval($this->total_amount), 2);
}

And then use as:

$item->totalAmountFormatted();
1 like
As3ad's avatar
Level 1

@Amaury that works, thank you very much. Why it doesn't work in accessor? I don't want to go to every view and change the $invoice->total_amount to $invoice->totalAmountFormatted()

As3ad's avatar
Level 1

it looks like that is a laravel 9 problem. I updated to laravel 11 and it is working just fine.

Please or to participate in this conversation.