3 votes

How to calculate the discount percentage of the current price and the previous price?

How can I display the percentage in percentage % of as is value that is being applied to the discount of the product with the current price and the previous price.

Example:

If in the database I have the following records in the table products

id_pro     price     price_old
  1        50.00      100.00

The following message to show in the primer would be $50.00 / 50% discount

The query I do the following:

Note: The code PHP of the query is above the HTML

  if (isset($_GET['id'])){
    $id = $_GET['id'];
    $sql = "SELECT * FROM products WHERE url='".$id."'";
    $result = mysqli_query($con, $sql);

    if(mysqli_num_rows($result) > 0){
        while ($row = mysqli_fetch_array($result)) {
            $id = $row['id_pro'];
            $price = $row['price'];
            $price_old = $row['price_old'];
        }
    }
  }

The results of the query show it as follows, within any content, HTML.

<?php echo $price; ?>

My idea is to be able to take the value of the two variables $price and $price_old and by means of them to show what percentage discount is being performed.

Note: Always when taking into consideration whether or not there is a previous price recorded in the table, some products will not have record of a previous price in this case would not exist a discount percentage in the column price_old table products

My idea would be something like that, but I have problems in approach of the code PHP to show the percentages taking account of the current price and the previous price.

}else{
  echo "Aquí el porcentaje -> 50% de descuento";
}else {
  echo "No existe descuento -> En este caso no se mostrara un texto, quedara un echo vació";
}

3voto

Matias Olivera Points 1072

You can use the rule of three, simple to calculate the percentage, where it multiplies the numbers crossed and divided it by the that is only.

Assuming that we have a product with a price above $120, and a current price of $60, the calculation would be as follows:

$120 -> 100%
$60  -> x

x = (60 * 100) / 120
x = 50%

The value of x is only the percentage difference that exists between both prices. To know the discount of the product it only remains to calculate the difference between 100% and x.

In PHP would look like:

// Si existe el precio anterior
if ($price_old != null) {
    // Se calcula el porcentaje de descuento
    $descuento = 100 - ($price * 100 / $price_old);
    // Se asigna a mensaje el precio y el descuento
    $mensaje = "$" . price . "/" . $descuento . "% de descuento";
} else {
    // Se asigna solamente el precio a mensaje 
    $mensaje = "$" . price;
}

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X