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.
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)