Search code examples
phpcart

Shopping cart calculating total


Good day, below is a piece of code that increments the total cost for each product in the session array. My problem is displaying 0 at the end of the total when the last peny = 0.

Example 1, 2.20 + 2.20 = 4.40 but only 4.4 is shown

Example 2, 2.20 + 2.25 = 4.45 and 4.45 is shown

$total = 0;
if (isset($_SESSION['cartItems'])){
    foreach ($_SESSION['cartItems'] as $product){
        $total += $product['cost'];
    }
}
echo $total;

Any advice on how to show/include when a 0 is entered?


Solution

  • This was already answered in a comment by WebCode.ie but here is a detailed answer that may help those facing the same problem:

    To customize a number format, you can use the PHP Function string number_format() , that accepts either one, two, or four parameters, this way:

    $my_number=25200;    
    $number_decimals=2;
    $dec_separator=".";
    $thousands_separator=" ";
    
    echo number_format($my_number , $number_decimals, $dec_separator, $thousands_separator);
    
    // This will output 25 200.00 
    
    1. The number you want to format
    2. The number of decimals
    3. The decimal separator
    4. The thousands separator

    Please also note that you can only use 1, 2 or 4 parameters.