Reputation: 198
Ik keep getting wrong amounts when I want to sum prices and then add VAT to it. I have the following situation:
Let's say I have 4 products and I want them show them on a invoice. Each products has the same price of 2.50.
I have the following code:
@products = Product.find([1,2,3,4])
On the invoice I have:
@products.each do |product|
%p
Price without VAT:
= number_to_currency(product.price) --> Gives € 2,50
%p
Price with 21% VAT:
= number_to_currency(product.price / 100 * 121) --> Gives € 3,03
This shows like this:
Now I want to add a total line. I have tried something like this:
- sum = @products.sum( &:price ) --> Gives 10
%p
Total with 21% VAT:
= number_to_currency(sum / 100 * 121 ) --> Gives € 12,10 instead of € 12,12
What I try, I keep getting a total price including VAT on € 12.10 instead of € 12,12. (4 x € 3,03 = € 12,12)
I have the price in my database as:
t.decimal "price"
The price is stored as 2.5
Who can help me out with this?
Upvotes: 0
Views: 136
Reputation: 52357
One product's correct VAT amount:
(BigDecimal.new("2.5") / 100 * 121).to_f #=> 3.025
4 products correct VAT amount:
(BigDecimal.new("10") / 100 * 121).to_f #=> 12.10
Options:
Applying what's said above, 1 product with VAT:
(product.price / 100 * 121).round(2)
all products with VAT:
products.sum { |p| (p.price / 100 * 121).round(2) }
Upvotes: 3