Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

currency format in laravel

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.

like image 912
Johnny Avatar asked Oct 20 '17 11:10

Johnny


2 Answers

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)
like image 110
Gijs de Jong Avatar answered Nov 16 '22 18:11

Gijs de Jong


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)
like image 22
Cédric Avatar answered Nov 16 '22 17:11

Cédric