在Laravel中使用number_format方法

Hay*_*kar 29 php laravel

我在Laravel和Blade模板中相当新.
任何人都可以帮我告诉我该怎么做?

我有这样的观点:

@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
Run Code Online (Sandbox Code Playgroud)

我希望$Expense->price$Expense->amount格式化.
我尝试在$Expense->amountas 上使用它,number_format($Expense->amount)但它没有用.

tee*_*eyo 75

这应该工作:

<td>{{ number_format($Expense->price, 2) }}</td>
Run Code Online (Sandbox Code Playgroud)

  • 有关 PHP 的 `number_format()` 函数的更多详细信息:http://php.net/manual/en/function.number-format.php (2认同)

小智 8

如果你使用Eloquent,在你的模型中放:

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

获取价格属性是您在数据库中的字段.得到一些属性.

  • 就个人而言,使用这个答案我会将`sprintf`移动到一个可重用的组件,如`App\Localization\Currency :: format($ price)`,如果它需要灵活而没有太多的抽象.但无论哪种方式,这都是一个答案 (2认同)

Joa*_*her 6

如果您使用的是Eloquent,最好的解决方案是:

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

因此,现在您必须在模型中附加formattedPrice,并且可以同时使用price(处于其原始状态)和formattedPrice。