我有這樣的代碼:如何避免零誤差的分割?
add_filter('woocommerce_sale_flash2', 'lx_custom_onsale_label', 10, 2);
function lx_custom_onsale_label() {
global $product;
$percentage = round((($product->get_regular_price() - $product->get_sale_price())/$product->get_regular_price() ) * 100);
$absolute = round((($product->get_regular_price() - $product->get_sale_price())));
if ($product->get_regular_price() > 100) {
return '<span class="onsalex bg_primary headerfont">'. sprintf(__(' -%s', 'salex'), $absolute . ',-').'</span>';
}
else if ($product->get_regular_price() < 1) {
return '<span class="onsalessszzzx bg_primary headerfont">'. sprintf(__(' -%s', 'salex'), $absolute . ',-').'</span>';
}
else {
return '<span class="onsalexzzz bg_primary headerfont">'. sprintf(__(' -%s', 'salex'), $percentage . '%').'</span>';
}
}
一切工作正常,除了當分隔爲O型,通知會顯示:
警告:被零除在 d:\ SERVER \ InstantWP_4 .3.1 \ iwpserver \ htdocs中\ WordPress的\可溼性粉劑內容\主題\的MyTheme \ functions.php的上線553 553
線路是這樣的代碼:
$percentage = round((($product->get_regular_price() - $product->get_sale_price())/$product->get_regular_price() ) * 100);
我不明白如何避免條件爲零的警告代碼。
非常感謝您的幫助。
厚臉皮回答:*不要除以零* – domsson
在執行操作之前,只需測試'$ product-> get_regular_price()'是否大於0 – kaldoran
'如果'真的很方便如果你不想做點什麼 – Peter