php 在 Laravel 中使用 number_format 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27651808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using number_format method in Laravel
提问by Hayatu Mohammed Abubakar
I am fairly new in Laravel and Blade templating.
Can anyone help show me how to do this?
我对 Laravel 和 Blade 模板相当陌生。
谁能帮我看看如何做到这一点?
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.
我希望$Expense->price
和$Expense->amount
被格式化。
我尝试在$Expense->amount
as上使用它,number_format($Expense->amount)
但没有用。
回答by teeyo
This should work :
这应该工作:
<td>{{ number_format($Expense->price, 2) }}</td>
回答by Jonathan Borges
If you are using Eloquent, in your model put:
如果您使用 Eloquent,请在您的模型中输入:
public function getPriceAttribute($price)
{
return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));
}
Where getPriceAttribute is your field on database. getSomethingAttribute.
哪里获取价格属性是您在数据库中的字段。获得某物属性。
回答by Joaquin Marcher
If you are using Eloquent the best solution is:
如果您使用 Eloquent,最好的解决方案是:
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.
所以现在你必须在你的模型中附加 formattedPrice 并且你可以同时使用 price(原始状态)和 formattedPrice。
回答by 8ctopus
Here's another way of doing it, add in app\Providers\AppServiceProvider.php
这是另一种方法,在 app\Providers\AppServiceProvider.php 中添加
use Illuminate\Support\Str;
...
public function boot()
{
// add Str::currency macro
Str::macro('currency', function ($price)
{
return number_format($price, 2, '.', '\'');
});
}
Then use Str::currency() in the blade templates or directly in the Expense model.
然后在刀片模板中或直接在费用模型中使用 Str::currency() 。
@foreach ($Expenses as $Expense)
<tr>
<td>{{{ $Expense->type }}}</td>
<td>{{{ $Expense->narration }}}</td>
<td>{{{ Str::currency($Expense->price) }}}</td>
<td>{{{ $Expense->quantity }}}</td>
<td>{{{ Str::currency($Expense->amount) }}}</td>
</tr>
@endforeach