Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

PHP percentage difference returning incorrect

I'm trying to display the percentage difference in price. i.e. Save 20%, but the output is different from what's expected.

89.99 - 64.99 returns 99.32

129.99 - 89.99 returns 10.21

169.99 - 119.99 returns 99.86

Based on the code here: http://thisinterestsme.com/php-percentage-difference/

Currency symbol removed using this suggestion: How to get the price value without currency symbol?

    $oldPrice = wc_price($product->get_regular_price());
    $newPrice = wc_price($product->get_sale_price());

    $pricenocurrency = $oldPrice;
    $pricenocurrency2 = $newPrice;
    $pricenocurrency = preg_replace( '/[^.\d]/', '', $pricenocurrency  );
    $pricenocurrency2 = preg_replace( '/[^.\d]/', '', $pricenocurrency2  );

    $percentChange = ($pricenocurrency2 / $pricenocurrency) * 100;

echo number_format($percentChange, 2)

Comments