Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using number_format method in Laravel

Tags:

php

laravel

I am fairly new in Laravel and Blade templating.
Can anyone help show me how to do this?

I have a view like this:

@foreach ($Expenses as $Expense)
    <tr>
        <td>{{{ $Expense->type }}}</td>
        <td>{{{ $Expense->narration }}}</td>
        <td>{{{ $Expense->price }}}</td>
        <td>{{{ $Expense->quantity }}}</td>
        <td>{{{ $Expense->amount }}}</td>                                                            
    </tr>
@endforeach

I want the $Expense->price and$Expense->amount to be formatted.
I tried using it on the $Expense->amount as number_format($Expense->amount) but it didn't work.

like image 875
Hayatu Mohammed Abubakar Avatar asked Dec 26 '14 00:12

Hayatu Mohammed Abubakar


People also ask

How to change number format in PHP?

PHP's number_format() function gives you an easy way to format numbers for displaying to the user. You can separate thousands with commas or other separators, choose the decimal point character, and choose the number of decimal places to display (or display no decimals at all).

How to add number format in PHP?

PHP | number_format() Function $number: It is required parameter which specified the number to be formatted. If no other parameters are set, the number will be formatted without decimals and with the comma (, ) as the thousands separator. $decimals: It is optional parameter and used to specifies decimals.

How can I set 2 decimal places in PHP?

$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Show activity on this post. This will give you 2 number after decimal.


3 Answers

This should work :

<td>{{ number_format($Expense->price, 2) }}</td>
like image 75
teeyo Avatar answered Oct 08 '22 06:10

teeyo


If you are using Eloquent, in your model put:

public function getPriceAttribute($price)
{
    return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));
}

Where getPriceAttribute is your field on database. getSomethingAttribute.

like image 22
Jonathan Borges Avatar answered Oct 08 '22 06:10

Jonathan Borges


If you are using Eloquent the best solution is:

public function getFormattedPriceAttribute()
{
    return number_format($this->attributes['price'], 2);
}

So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.

like image 14
Joaquin Marcher Avatar answered Oct 08 '22 07:10

Joaquin Marcher