How can i fix Warning: Division by zero in OpenCart

I have add below code for percentage discount badge(It automatically calculates the percentage between the old and new price.) for product. So, It is working fine.

But When, add 0.00 price in product. so. get error. Warning: Division by zero in /home/......

So, any solution for this error. How can i fix it?

below code add in .php file

'saving'    => round((($product_info['price'] - $product_info['special'])/$product_info['price'])*100, 0)

below code add in .tpl file

<span class="saving">-<?php echo $product['saving']; ?>%</span>

Thanks.


As the message explains: Do not divide through zero. Your Price is zero.

Option 1: Write a Function

$array = [
'foo' => 'bar',
'donald' => 'duck',
'saving' => GetDiscount($product_info['price'], $product_info['special'])
]

//Get the Discount. If the Price is zero, Discount is 100 %
function GetDiscount($price, $special) {
    return $price === 0 ? 100 : round((($price - $special)/$price)*100, 0);
}

Option 2: One Line

$array = [
'foo' => 'bar',
'donald' => 'duck',
'saving' => $product_info['price'] === 0 ? 100 : round((($product_info['price'] - $product_info['special'])/$product_info['price'])*100, 0)
]
链接地址: http://www.djcxy.com/p/69366.html

上一篇: 为什么我在这里通过零错误得到一个分区?

下一篇: 我如何解决警告:在OpenCart中除零