문제

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)
]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top