2017-04-13 5 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でのゼロによる除算:\サーバー\ InstantWP_4を.3.1 \ iwpserver \ htdocsに\ワードプレス\ WP-コンテンツ\テーマ\ライン上で553

ライン553は、このコードでMYTHEME \のfunctions.php:

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

このコードで条件ゼロの警告を回避する方法はわかりません。

本当に助けていただきありがとうございます。

$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

'if'は本当に便利です。何かしたくない場合は – Peter

答えて

1

は交換してください

$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

関連する問題