I'm trying to understand how Magento handles the order totals and trying to replicate the same behaviour for a Magento 2 Module.
This is one of the most weird cases or as we call it, the "100 Coffees Problem".
The price of each coffee (without VAT) is 0,49€.
Each coffee has a VAT of 23% applied.
If we have 10 rows of 10 coffees each, we get this totals:
Subtotal: 49,00 €
Tax: 11,30 €
Grand Total: 60,30 €
But if we have for example 1 row of 100 coffees, we have the following totals:
Subtotal: 49,00 €
Tax: 11,27 €
Grand Total: 60,27 €
I know this is a corner case and that the Grand Totals will be wrong, but how does it get to 11,30€ in taxes?
Also, another case that we found during our module development, is for example:
Three products of 10,65€ (No VAT) + 23% VAT
One product of 10,20€ (No VAT) + 23% VAT
And the end totals are:
Subtotal: 42,16 €
Tax: 9,70 €
Grand Total: 51,85 €
How do can I do my cals right so that I get the same totals?
You're absolutely right, these are interesting edge cases related to how Magento 2 handles order totals with VAT (Value Added Tax). Here's a breakdown of what's happening and how to achieve the same behavior in your module:
1. The "100 Coffees Problem"
The difference in tax amounts arises due to rounding during calculations. Magento likely performs calculations with a higher precision than what's displayed on the frontend.
Scenario 1 (10 rows of 10 coffees):
Scenario 2 (1 row of 100 coffees):
Solution:
In your module, you can achieve the same behavior by:
2. Multiple Products with VAT
This case might involve a similar rounding issue, or it could be related to how Magento handles individual product tax calculations before summing them up. For more info check here.
Solution:
Additional Tips:
By following these steps and understanding the potential rounding issues, you can ensure your custom module calculates order totals and tax amounts consistently with Magento's core functionality.
The "100 Coffees Problem" is a common challenge in Magento 2 due to rounding during tax calculations. Magento calculates tax per item before rounding, then rounds the subtotal and tax separately. This can lead to slight discrepancies, especially with a large number of items.
In your scenario, with 10 coffees, the per-item rounding adds up to the expected €1.10 tax. But with 100 coffees, those small rounding errors can accumulate, resulting in a slightly different final tax amount (e.g., €1.12 or €1.13) after rounding.
To achieve more consistent tax calculations in your module, consider rounding the total tax for all items before applying individual rounding. This minimizes the impact of accumulated errors. You could also define a specific number of decimal places to maintain consistency throughout calculations. You can check the Vally Plant Training as well for training.