2017-04-13 65 views
-6

我有這樣的代碼:如何避免零誤差的分割?

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); 

我不明白如何避免條件爲零的警告代碼。

非常感謝您的幫助。

+8

厚臉皮回答:*不要除以零* – domsson

+0

在執行操作之前,只需測試'$ product-> get_regular_price()'是否大於0 – kaldoran

+1

'如果'真的很方便如果你不想做點什麼 – Peter

回答

1

替換:

$percentage = round((($product->get_regular_price() - $product->get_sale_price())/$product->get_regular_price() ) * 100); 

由:

$percentage = 0; 
if ($product->get_regular_price() > 0) 
    $percentage = round((($product->get_regular_price() - $product->get_sale_price())/$product->get_regular_price() ) * 100); 

奇怪的答案,我知道,但如果你不除以零,沒有任何錯誤。

解釋

由於@domdom指出「不要零分」,這是這裏一個很好的答案,並通過零,因爲分一個很好的做法是不是在數學「合法」的。

+0

這是工作,正是我需要的。謝謝。 – Mailmulah

+0

然後請使用upvote按鈕下方的複選標記來驗證答案。謝謝 – kaldoran

0
if($product->get_regular_price()> 0) 
{ 
//do your work 
} 

只要在分割前檢查價格是否爲零。

0

只是檢查是否$product->get_regular_price()大於/不等於零(如果負值是可能的):

if ($product->get_regular_price() != 0){ 
    // Do stuff 
} else { 
    // Do something with the zero 
} 

由於只有正數:

if ($product->get_regular_price() > 0){ 
    // Do stuff 
} else { 
    // Do something with the zero 
} 
+0

上面的答案是工作,但我也嘗試你的代碼。謝謝。 – Mailmulah