3 ms·
> Obviously the final amount could be stored as an integer in cents, but I'm talking about the tax rate and the calculations of it. The tax rate (like most thi
by dragonwriter 7y ago
> Obviously the final amount could be stored as an integer in cents, but I'm talking about the tax rate and the calculations of it.
The tax rate (like most things associated with money) should be stored as an exact decimal (fixed point decimal, decimal floating point, or arbitrary precision decimal all work.)
> I guess you need to calculate the tax for each item, round it to cents (and I assume the rules on how you round can vary by jurisdiction, so it's not just calling your language's round function), multiply that by the quantity of that item (good luck if the quantity can be a decimal value), then sum each line item.
Usually taxes are required to be calculated by summing the pre-tax cost of all line items, applying the tax rate, rounding by the applicable rules, and then adding that to the pre-tax subtotal to get the final total. But having decimal unit prices (even decimal cents, e.g., gas is usually priced in mils, not cents), decimal quantities, and decimal tax rates are all non-problems (so no "good luck" needed) as long as you are using an exact decimal representation rather than binary floating point.
- jaclaz 7y agoTo be fair, there are a range of little issues when applying tax rates, not connected to the representation of the numbers involved. In Italy the generic VAT rate is 22%. When you expose a price (to the final customer) it is always included VAT, but VAT needs to be explicited on fiscal documents (receipt and/or invoices). So you have an article priced to the public Euro 2,69 (included 22% VAT), what is the net price and how much is the VAT? 2,69/1,22=2,204918... So, let's try rounding it to 2,20: 2,20x0,22=0,484=0,48 no, wait, 2,20+0,48=2,68 Ok, let's try rounding it to 2,21: 2,21x0,22=0,4862=0,49 no, wait, 2,21+0,49=2,70 You have to use the first and add 0,01 to the VAT to have it work: 2,20+(0,48+0,01)= 2,69