17

I am using currency format in lots of places in my blade files. I am using number_format to show a proper currency format. So it looks like this

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

if I don't use it it looks like this

<p>${{ $row->nCashInitialBalance }}</p> // $1123
<p>${{ $row->nCashCalculatedBalance }}</p> // $300.5
<p>${{ $row->nCashPaymentsReceived }}</p> // $2341.15
<p>${{ $row->nCardFinalBalance }}</p> // $234.1

Also for the input fields I am using toFixed(2) in lots of places.

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

Isn't there an easiest way to show all the variables as proper currency format? I have used number_format and toFixed(2) almost more then 50 times now.

Johnny
  • 386
  • 1
  • 3
  • 11

9 Answers9

50

You could create a custom Laravel directive. You still need to call that directive at every place you need it but comes with the benefit that if you ever want to change the code (e.g. replace number_format with something else) you only have to update that directive.

Example (taken from the docs and updated for your use case) (in your AppServiceProvider boot method):

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

To use it in Blade:

@convert($var)
Gijs de Jong
  • 967
  • 9
  • 14
  • I guess it is shorter thàn writing ```number_format($money, 2)``` each time. if I use money_format ( https://github.com/cknow/laravel-money). would I still need to wrap the variable? ie @money(500, 'BRL') ? – Johnny Oct 20 '17 at 12:45
  • Not necessarily I think, but if you do you get the benefit of only having the specific code in one place, making it easier to change it if you ever find another package for example. The included Blade directives in that package do look nice. – Gijs de Jong Oct 20 '17 at 18:55
  • @jonlink actually that is not true. The function `money_format` will be deprecated in PHP7.4, not `number_format`. – Gijs de Jong Feb 04 '20 at 15:42
  • @GijsdeJong whoops my mistake. Must've had a brain fart. No need to get defensive, my friend. I'll delete the comment. Thanks for the catch. – jonlink Feb 05 '20 at 16:17
  • Nice idea. The directive name could use some work though. No one would know what `@convert()` actually does. – jonlink Feb 05 '20 at 16:20
  • Sweet. I'd add `number_format($money, 2, , ',', '.');` parameters if you want an output like $X.XXX,XX or something. Thanks – Jean Manzo Feb 04 '21 at 15:18
23

You can add a custom Blade directive in the boot() method in your AppServiceProvider.php file.

For example:

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

And in your Blade file, you will just have to use @money() like this:

@money($yourVariable)
Cédric
  • 467
  • 2
  • 9
10

I would most not use a "directive"... I found it cleaner to do the same logic as an accessor on the model.

public function getAmountAttribute($value)
{
    return money_format('$%i', $value);
}
Robert Kehoe
  • 421
  • 5
  • 7
1

You can use PHP's built-in NumberFormatter. For Laravel, wrap it in a directive or use in an accessor in the model, its up to you OR it depends on the situation where you exactly need the formatting.

  • This is supported in PHP 8
  • A multi-purpose class to format different types of numbers including currency, amounts in decimal numbers, percent values etc.
  • Its based on country/region locale, for example en_US

OOP Style

$amount = new NumberFormatter("en_US", NumberFormatter::CURRENCY);
echo $amount->formatCurrency(1123, 'USD'); // outputs $1,123.00

Procedural Style

$amount = numfmt_create( 'en_US', NumberFormatter::CURRENCY );;
echo numfmt_format_currency($amount, 1123, 'USD'); // outputs $1,123.00
Usman
  • 43
  • 5
1

You can create helper functions to use in Blade:

In app/Helpers.php:

<?php

function toCurrency($value, $currency, $fractionDigits = 0)
{
    $acceptedCurencies = ["USD" => "en_US", "VND" => "vi_VN"];

    if (!in_array($currency, array_keys($acceptedCurencies)))
        return $value;

    if (!is_numeric($value))
        return $value;

    $formatter = new NumberFormatter($acceptedCurencies[$currency], NumberFormatter::CURRENCY);
    $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $fractionDigits);
    $formattedNumber = $formatter->format($value);

    return $formattedNumber;
};

In app/Providers/AppServiceProvider.php:

public function boot(): void {
    require_once app_path('Helpers.php');
}

In Blade:

{{ toCurrency($item->price, "USD") }}

Result: $1,000,000

ngosangns
  • 11
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 31 '23 at 19:15
0

If you want to format negative numbers, you'll need to do it this way:

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

In your blade file use:

@money(-10)

If you make edits to your directive, you'll need to clear your view:

php artisan view:clear
stillatmylinux
  • 1,399
  • 13
  • 25
0

If you are using Laravel Cashier you can use the Laravel built-in formatAmount() method.
In your boot() method in AppServiceProvider

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

In your blade view Total: @money($proudct->price)

Output- Total: £100.00

Note:

  • Don't forgot to importing
  • Clear config (if needed) php artisan config:clear
Sarwar Ahmed
  • 588
  • 2
  • 6
  • 14
0

Check out my money package for PHP (Laravel).

In the config you can choose a number of decimal places after the decimal point and money origin (int or float):

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

After that, all money objects will have 2 decimal places. For INT origin 100$ will be as 10000 (100 * 10^2) number.

Then create an instance and display it:

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

You can add easily customize displaying of each object by passing it to the money() helper function or you can apply it for all further objects by setting up the config file.

-6

Use this solution:

{{"$ " . number_format($data['total'], 0, ",", ".")  }}
Claudius
  • 1
  • 2