Forza
Forza

Reputation: 1649

PHP: How to display decimal numbers in an array?

This is a tricky question to ask. A friend of mine seeks help, and I am not really into the project so it is difficult to describe the problem.

He has a shopping cart written in PHP, and in that shopping cart he wants all the product prices to be counted into a total price.

The problem is, all the prices are in a MySQL database. Displaying the prices (with decimals) is not a problem but, when these prices are counted and put in a variable, the decimals are not shown.

How can we solve this problem?

I will show you the code that he uses for displaying the prices in the shopping cart:

// Show cart
foreach($cart as $products) {
  // Split
  /*
    $product[x] -->
       x == 0 -> product id
       x == 1 -> hoeveelheid
  */
  $product = explode(",",$products);

  // Get product info

  $sql = "SELECT product_nummer, productnaam, verkoopprijs
         FROM product
         WHERE product_nummer = ".$product[0];  // Komt uit de sessie
  $query = mysql_query($sql) or die (mysql_error()."<br>in file ".__FILE__." on line ".__LINE__);
  $pro_cart = mysql_fetch_object($query);
  $i++;
  $price = $pro_cart->verkoopprijs; // variable price aanmaken zodat er opgeteld wordt

  echo "<tr>\n";
  echo "  <td>"."&nbsp;&nbsp;&bull;&nbsp;".$pro_cart->productnaam."</td>\n";     // naam
  echo "  <td><input type=\"hidden\" name=\"productnummer_".$i."\" value=\"".$product[0]."\" />\n"; // wat onzichtbare vars voor het updaten
  echo "      <input type=\"text\" name=\"hoeveelheid_".$i."\" value=\"".$product[1]."\" size=\"2\" maxlength=\"2\" /></td>\n";
  echo "  <td class=\"rechtsuitlijnen\">"."&#8364;&nbsp;".$pro_cart->verkoopprijs."</td>"."\n";
  $lineprice = $product[1] * $price;      // regelprijs uitrekenen > hoeveelheid * prijs
  echo "  <td class=\"rechtsuitlijnen\">"."&#8364;&nbsp;".$lineprice."</td>\n";
  echo "  <td><a href=\"javascript:removeItem(".$i.")\">X</td>\n"; //Product verwijderen
  echo "</tr>\n";


  // Total
  $total = $total + $lineprice; // Totaal updaten
}
?>

Upvotes: 1

Views: 3983

Answers (3)

Boopathi
Boopathi

Reputation: 166

string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

Check out number_format documentation.

Upvotes: 1

Alex M
Alex M

Reputation: 3513

For displaying formatted numbers, you can use the PHP sprintf function ( http://php.net/manual/en/function.sprintf.php )

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?>

Upvotes: 2

Jules
Jules

Reputation: 7223

Use: bcadd()

echo bcadd(10.50, 12.75, 2);

returns 23.25

Upvotes: 1

Related Questions