Magento – Magento 2 Get Product Price Including Tax

magento2tax

I have simple product name is "Test Product" with Price = 100$
Also, I assign the tax class name "Default" with 7% Tax Rate

So how can I Calculate the product price including tax?

Default.phtml

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$ProductId = 1;
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($ProductId);    
$taxCalculation = $objectManager->create('\Magento\Tax\Api\TaxCalculationInterface');
$scopeConfig = $objectManager->create('\Magento\Framework\App\Config\ScopeConfigInterface');    

if ($taxAttribute = $product->getCustomAttribute('tax_class_id')) {
    $productRateId = $taxAttribute->getValue();        
    $taxCalculation = $objectManager->create('Magento\Tax\Model\Calculation\Rate')->load($productRateId);
    $rate = $taxCalculation->getRate();

    if ((int) $scopeConfig->getValue('tax/calculation/price_includes_tax', \Magento\Store\Model\ScopeInterface::SCOPE_STORE) === 1) {
        $priceExcludingTax = $product->getPrice() / (1 + ($rate / 100));
    } else {
        $priceExcludingTax = $product->getPrice();
    }        
}
$priceIncludingTax = $priceExcludingTax + ($priceExcludingTax * ($rate / 100));

Thanks in Advance!

Best Answer

Simply use Magento\Catalog\Helper\Data::getTaxPrice($product, $product->getFinalPrice(), true)

EDIT with code example:

In your constructor, inject like this:

public function __construct(\Magento\Catalog\Helper\Data $taxHelper) {
    $this->taxHelper = $taxHelper;
}

...and use it in your code like this:

public function doSomething($product) {
    $price = $this->taxHelper->getTaxPrice($product, $product->getFinalPrice(), true);
    // do something with the price
}
Related Topic