How not to have Warning if I leave empty in the discount multiplication formula?

0

How can I not have Warning: Division by zero in if I choose even to put zero. I want to have the option to leave the price empty, but if I leave empty, it multiplies as it is in the discount formula and gives error. You can not show this div if deal_price and deal_sale_price are empty or 0?

<ul class="deal-single-value">
    <?php
      $deal_price = get_post_meta( get_the_ID(), 'deal_price', true);
      $deal_sale_price = get_post_meta( get_the_ID(), 'deal_sale_price', true);
    ?>

    <li>
        <p><?php esc_html_e( 'Preço Antigo', 'site' ) ?></p>
        <?php echo site_format_price_number( $deal_price ) ?>
    </li>
    <li>
        <p><?php esc_html_e( 'Desconto de', 'site' ) ?></p>
        <?php echo round( 100 - ( $deal_sale_price / $deal_price ) * 100 ).'%'; ?>
    </li>
    <li>
        <p><?php esc_html_e( 'Você economizou', 'site' ) ?></p>
        <?php echo format_price_number( $deal_price - $deal_sale_price ) ?>
    </li>
</ul>
    
asked by anonymous 20.10.2016 / 04:19

2 answers

0

Just put a if before doing the calculation:

<ul class="deal-single-value">
<?php
  $deal_price = get_post_meta( get_the_ID(), 'deal_price', true);
  $deal_sale_price = get_post_meta( get_the_ID(), 'deal_sale_price', true);
?>

<li>
    <p><?php esc_html_e( 'Preço Antigo', 'site' ) ?></p>
    <?php echo site_format_price_number( $deal_price ) ?>
</li>

<?php if(!empty($deal_sale_price) && !empty($deal_price)):?>
<li>
    <p><?php esc_html_e( 'Desconto de', 'site' ) ?></p>
    <?php echo round( 100 - ( $deal_sale_price / $deal_price ) * 100 ).'%'; ?>
</li>
<?php endif;?>

<li>
    <p><?php esc_html_e( 'Você economizou', 'site' ) ?></p>
    <?php echo format_price_number( $deal_price - $deal_sale_price ) ?>
</li>

    
20.10.2016 / 14:30
0

The divisor can not be zero because no number is divisible by zero.

See an example of how you can solve by applying a ternary conditional.

<?php echo round( 100 - ($deal_price > 0?($deal_sale_price / $deal_price):0) * 100 ).'%'; ?>
    
20.10.2016 / 14:43