Mailmulah Mailmulah - 8 months ago 39
PHP Question

How do I avoid division by zero error?

I have a code like this:

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', 'luxewoo' ), $absolute . ',-' ).'</span>';
}

else if ($product->get_regular_price() < 1) {
return '<span class="onsalessszzzx bg_primary headerfont">'. sprintf( __(' -%s', 'luxewoo' ), $absolute . ',-' ).'</span>';
}

else {
return '<span class="onsalexzzz bg_primary headerfont">'. sprintf( __(' -%s', 'luxewoo' ), $percentage . '%' ).'</span>';
}
}


Everything work fine except when the divider is O, the notify will show:


Warning: Division by zero in
D:\SERVER\InstantWP_4.3.1\iwpserver\htdocs\wordpress\wp-content\themes\MYTHEME\functions.php on line 553


Line 553 is this code:

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


I don't understand how to avoid the warning with the condition zero on that code.

Really appreciate for the help.

Answer Source

Replace :

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

by :

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

Strange answer I know, but if you don't divide by zero, there is no error.

Explain :

As @domdom point out "Don't divide by zero" which is here a good answer, and a good practice since divide by zero is not "legal" in mathematics.