PHP Eliminate null at the end of my number

It's in Laravel, which probably doesn't matter.

<?php $totalprice = 0 ?> @foreach ($items as $item) <?php $totalprice = $totalprice + $item->net_price ?> @endforeach

      

$ item-> net_price can start at 884.80, but if it ends at 1204.30 it will display as 1204.3. Since this is a cost calculation, I would prefer that zero remain at the end.

Simple question but I'm a noob :( How can I fix this? Can't google it.

+3


source to share


3 answers


You can use 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 have moved the $ totalprice variable into the loop so that it goes all the way to reset to zero.

NB PHP must be 4.3+ and the server must be strfmon capable.

+1


source


Try with number_format()

.

echo number_format(100000000, 2, '.', '');

      



If you want the delimiter format ,

just add ,

to the last parameter. Get details here

0


source


Continuing my comment on the question, you should use a function number_format

.

string number_format (float $ number, int $ decimals = 0, string $ dec_point = ".", string $ thousand_sep = ",")

So this usage would do the job:

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, '.', ''); ?>

      

0


source







All Articles