laravel 中的货币格式

currency format in laravel

我在 blade 文件的很多地方都使用了货币格式。我正在使用 number_format 来显示正确的货币格式。所以看起来像这样

<p>${{ number_format($row->nCashInitialBalance, 2) }}</p> // ,123.00
<p>${{ number_format($row->nCashCalculatedBalance, 2) }}</p> // 0.50
<p>${{ number_format($row->nCashPaymentsReceived, 2) }}</p> // ,341.15
<p>${{ number_format($row->nCardFinalBalance, 2)}}</p> // 4.10

如果我不使用它,它看起来像这样

<p>${{ $row->nCashInitialBalance }}</p> // 23
<p>${{ $row->nCashCalculatedBalance }}</p> // 0.5
<p>${{ $row->nCashPaymentsReceived }}</p> // 41.15
<p>${{ $row->nCardFinalBalance }}</p> // 4.1

还有我在很多地方使用 toFixed(2) 的输入字段。

#nDiscount_fixed").val() = parseFloat( $("#nDiscount_fixed").val()).toFixed(2);

没有一种最简单的方法可以将所有变量显示为正确的货币格式吗?我现在使用 number_formattoFixed(2) 差不多超过 50 次了。

您可以在 AppServiceProvider.php 文件的 boot() 方法中添加一个 custom Blade directive

例如:

Blade::directive('money', function ($amount) {
    return "<?php echo '$' . number_format($amount, 2); ?>";
});

在你的 Blade 文件中,你只需要像这样使用 @money()

@money($yourVariable)

您可以创建一个 custom Laravel directive。您仍然需要在每个需要的地方调用该指令,但这样做的好处是,如果您想要更改代码(例如,将 number_format 替换为其他内容),您只需更新该指令即可。

示例(取自文档并针对您的用例进行了更新)(在您的 AppServiceProvider boot 方法中):

Blade::directive('convert', function ($money) {
    return "<?php echo number_format($money, 2); ?>";
});

要在 Blade 中使用它:

@convert($var)

我最不会使用 "directive"...我发现在模型上执行与访问器相同的逻辑会更简洁。

public function getAmountAttribute($value)
{
    return money_format('$%i', $value);
}

如果你想格式化负数,你需要这样做:

Blade::directive('money', function ($amount) {
        return "<?php
            if($amount < 0) {
                $amount *= -1;
                echo '-$' . number_format($amount, 2);
            } else {
                echo '$' . number_format($amount, 2);
            }
        ?>";
 });

在您的 blade 文件中使用:

@money(-10)

如果您对指令进行编辑,则需要清除视图:

php artisan view:clear

使用这个解决方案:

{{"$ " . number_format($data['total'], 0, ",", ".")  }}

如果您正在使用 Laravel Cashier,则可以使用 Laravel built-in formatAmount() 方法。
AppServiceProvider

中的 boot() 方法中
Blade::directive('money', function ($expression) {
    return "<?php echo laravel\Cashier\Cashier::formatAmount($expression, 'gbp'); ?>";
});

在您的 blade 视图中 Total: @money($proudct->price)

Output- Total: £100.00

注:

  • 别忘了导入
  • 清除配置(如果需要)php artisan config:clear

查看 my money package PHP (Laravel)。

在配置中,您可以选择小数点后的小数位数和货币来源(整数或浮点数):

'decimals' => 2,
'origin' => MoneySettings::ORIGIN_INT,

之后,所有货币对象都将保留 2 位小数。 对于 INT origin 100$ 将作为 10000 (100 * 10^2) 数字。

然后创建一个实例并显示它:

money(10000)->toString(); // "$ 100"
money(10000, currency('RUB'))->toString(); // "100 ₽"

您可以通过将每个对象传递给 money() 辅助函数来轻松添加自定义显示,或者您可以通过设置配置文件将其应用于所有其他对象。