I'm trying to find the best way to calculate basket's prices and totals. All product prices are represented by figures with 2 decimal points, however, when discount is added to the basket of say 50%, this given for instance price of $37.27 ends up with figure $18.635 having 3 decimal places. Now I'd like the calculations to be accurate, but rounding 3 decimal figures doesn't always give the expected result.
Scenario
I have 5 products in my basket with the following, original prices:
- $80.00
- $189.62
- $37.27
- $43.75
- $105.34
Giving us total of $455.98
When I add a global discount of 50% - taking the total of figures above, this would give me $227.99
. Now, this would work fine if I don't have to obtain the figure for each item after the discount has been applied - and that is the case when I want to pass the items to the PayPal Express Checkout. Request will fail unless total equals total of all items in the basket.
The above figures after dividing each by 2 (50%) are:
- $40.00
- $94.81
- $18.635
- $21.875
- $52.67
Giving us precisely same total as when we divide the total by 2. Problem is that I do not want 3 decimal figures in my basket, so rounding them the result becomes:
- $40.00
- $94.81
- $18.64
- $21.88
- $52.67
which adds up to $228
, which when multiplied by 2 gives us a different figure to the one we originally had in the basket without discount being applied.
What is the best way to tackle this sort of scenarios?