phpopencartcalculation

Subtract tax from a price with tax in OpenCart?


How do I subtract all taxes from a price with tax in OpenCart?

In the example below I use the default "Taxable goods" tax setting from OpenCart, which is 20% VAT + $2,00 Eco-Tax.

$number = 20.80

// Get $number tax:
$tax = $this->tax->getTax( $number , $product_info['tax_class_id'] , $this->config->get('config_tax') );

// Subtract tax from total price:
$result = $this->currency->format( ( $number - $tax ) , $this->session->data['currency'] );

This returns an incorrect value of $14,64 because it calculates the tax on $number (20,80), which already is a price with tax. The correct price for $20,80 without tax should be $15,67

This should be the formula in this case: (20.80 - 2.00) / 120 * 100 = 15.6667

Is there any way to subtract all taxes from a price that already has tax included?


Solution

  • $taxRate = 20;
    
    $gross = 150;
    $divisor = (100 + $taxRate) / 100;
    $net = round( $gross / $divisor, 2);
    $tax = round( $gross - $net, 2 );
    
    Echo "Gross was $gross - Net is $net Tax is $tax";
    

    RESULT with 20% tax

    Gross was 150 - Net is 133.33 Tax is 16.67
    

    RESULT with 15% tax

    Gross was 150 - Net is 130.43 Tax is 19.57
    

    Try a few dry runs and then check with this code