Php 如何避免零误差除法?

Php 如何避免零误差除法?,php,wordpress,Php,Wordpress,我有这样一个代码: 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() ) / $produ

我有这样一个代码:

 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>';
    }
}
我不明白如何避免该代码上条件为零的警告

非常感谢您的帮助。

替换:

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

奇怪的答案我知道,但若你们不除以零,就并没有错误

解释

正如@domdom指出的,“不要被零除”,这是一个很好的答案,也是一个很好的实践,因为被零除在数学中是不合法的

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

只需在除法前检查价格是否为零。

只需检查
$product->get\u regular\u price()
是否大于/不等于零(如果可能为负值):

只有正数:

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

试试看。像这样的东西很简单但很有用

$var = @($val1 / $val2);
更换这条线

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


这个问题已经得到了回答,这只是使用十进制运算符的另一种方法。厚颜无耻的回答:不要被零除。只需在执行操作之前测试
$product->get\u regular\u price()
是否大于0如果你不想做某件事,那么
非常方便上面的答案就是工作,但我也尝试你的代码。谢谢。然后请使用upvote按钮下的复选标记验证答案。谢谢
if ($product->get_regular_price() > 0){
  // Do stuff
} else {
  // Do something with the zero
}
$var = @($val1 / $val2);
 $percentage = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 );
 $percentage = $product->get_regular_price() != 0 ? round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 ) : 0;