购物车计算总数

Shopping cart calculating total

美好的一天,下面是一段代码,它增加了会话数组中每个产品的总成本。我的问题是当最后一分钱 = 0 时,总数末尾显示 0。

示例 1,2.20 + 2.20 = 4.40 但仅显示 4.4

示例 2,显示 2.20 + 2.25 = 4.45 和 4.45

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

关于如何在输入 0 时 show/include 有什么建议吗?

WebCode.ie 已经在评论中回答了这个问题,但这里有一个详细的答案,可以帮助那些面临同样问题的人:

要自定义数字格式,您可以使用 PHP 函数 string number_format() ,它接受 onetwo,或者四个 参数,这样:

$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. 你要格式化的数字
  2. 小数位数
  3. 小数点分隔符
  4. 千位分隔符

另请注意,您只能使用 1、2 或 4 个参数。