Reputation: 51
This is in Laravel, which probably isn't relevant.
<?php $totalprice = 0 ?> @foreach ($items as $item) <?php $totalprice = $totalprice + $item->net_price ?> @endforeach
$item->net_price could start at 884.80 for example but if it ends on 1204.30 it will display as 1204.3. As this is a cost calculation I would prefer that zero to stay on the end.
Simple question but I'm a noob :( How do I fix this? Can't seem to find on Google.
Upvotes: 3
Views: 295
Reputation: 347
You can use the money_format() function (http://php.net/money_format)
For example:
class items{}
$item1 = new items();
$item1->net_price = "14.6";
$item2 = new items();
$item2->net_price = "12.50";
$items = [$item1, $item2];
//display a '£' symbol
setlocale(LC_MONETARY, 'en_GB.UTF-8');
foreach ($items as $item){
$totalprice = 0;
$totalprice = $totalprice + $item->net_price;
echo money_format('%.2n',$totalprice) . "\n";
}
Based on your original question the following should work:
@foreach ($items as $item)
<?php
$totalprice = 0;
$totalprice = $totalprice + $item->net_price;
$totalprice = money_format('%.2', $totalprice);
?>
@endforeach
I moved the $totalprice variable into the loop so that it gets reset to zero before it is used.
NB PHP needs to be 4.3+ and the server needs to be capable of strfmon.
Upvotes: 1
Reputation: 10346
In continuation of my comment to the question, you should use the number_format
function.
string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
So, this usage would do the work:
number_format($number, 2, '.', '');
In your code:
<?php $totalprice = 0 ?>
@foreach ($items as $item) <?php $totalprice += $item->net_price ?> @endforeach
<?php echo number_format($totalprice, 2, '.', ''); ?>
Upvotes: 0
Reputation: 31749
Try with number_format()
.
echo number_format(100000000, 2, '.', '');
If you want the ,
separator format then just add ,
to the last parameter. Will get details here
Upvotes: 0