Split reduction by items in shopping cart
I have an issue related to an ecommerce shopping cart. In certain circumstances (usually involving special offers or vouchers) a reduction might be made to the overall cart total - e.g. £10 voucher off total cart price. To calculate the tax part of this cart one of the suggestions by the tax office in the UK is to divide the reduction by the number of products in your cart and use this to calculate a new Gross (inc. tax) price for each product, from which you can calculate a new Net (excl. tax) price. For example: a £10 discount would be (in the case of 2 pro开发者_开发百科ds) £5 off gross of each. Obviously one problem here could be if one of the items is very cheap, e.g. £2.99 and therefore cannot take the £5 reduction.
I need a method of calculating what this reduction should be, so it splits evenly between the total number of products but never makes the cost of a single item less than zero. Help!
FWIW i will be programming this in PHP
EDIT
Oswald's example would give me something like this in PHP:
$prodA = 2.99;
$prodB = 20.00;
$total = ($prodA + $prodB);
$reduction = 5.00;
$newA = ($prodA - (($prodA/$total) * $reduction));
$newB = ($prodB - (($prodB/$total) * $reduction));
It seems to add up..
If item
is the gross price of an item, total
is the sum of all gross prices, and reduction
is the amount you want to subtract from the bill, then the new gross price for the item is
item - item/total * reduction
This obviously does not split the reduction evenly among the items. But splitting the reduction evenly among the items leads to problems (as you have noticed yourself).
Rather the method splits the reduction proportionally according to the price of the items. E.g if an item of 10$ is reduced by 1$, then an item of 20$ will be reduced by 2$ and item item of 5$ will be reduced by 0.5$.
The algorithm is simple:
- For each product calculate a relative factor (usually called 'weight' in maths), that is the price of a product divided by the cart price.
- Reduce the price of each product by its weight multiplied by the discount.
For example, if you have a £10 discount and 3 products: A (£2), B (£3), and C (£45), then the weights are:
- A: 2/(2+3+45) == 2/50 = 0.04
- B: 3/(2+3+45) == 3/50 = 0.06
- A: 45/(2+3+45) = 45/60 = 0.9
Therefore the new prices will be:
- A: £1.60 == £2 - £0.04*10
- B: £2.40 == £3 - £0.06*10
- A: £36.00 == £45 - £0.9*10
精彩评论