Reputation: 175
After pouring over several stackoverflow posts and many many websites, I am resorting to directly asking this question from the smarter folks here. Our platform deals with currency calculations for taxes, discounts, etc. We are currently focused on USD and CAD only. We are a pretty standard shop that is running our backend services on python and on the frontend, we have a few apps on iOS and Andriod.
We do all our calculations in our backend and we use python's decimal
for all our calculations and we quantize right before showing the values in our UI or actually processing payments. Our initial pricing is normal in cents and integers but can end up with values of upto 4 decimal places. This is where it gets interesting.
Here is a basic example:
*** These values are calculated in the backed ***
[1a] Price of item (in dollars): $3.75
[1b] Price of item (in cents): 375
[1c] Tax rate: 6.25%
[1d] Calculated tax (in cents): 23.4375 ( = 375 * 6.25%)
[1e] Tip: 15%
[1f] Calculated tip (in cents): 56.2500 ( = 375 * 15%)
[1g] Total (in cents): 454.6875 ( = 375 + 23.4375 + 56.2500)
[1h] Total (in dollars and rounded): $4.55
*** This is visible to user ***
[2a] Price of item (in dollars): $3.75
// Value for [2b] is taken and rounded from value of [1d]
[2b] Tax (in dollars and rounded): $0.23
// Value for [2c] is taken and rounded from value of [1f]
[2c] Tip (in dollars and rounded): $0.56
// Value for [2d] is taken and rounded from value of [1g]
[2d] Total (in dollars and rounded): $4.55
However, if you add [2a], [2b] and [2c], you get:
[2e] 3.75 + 0.23 + 0.56 = 4.54
As you can see [2e] and [1h] are off by a cent. What is the best way to calculate and display currency amounts.
Upvotes: 0
Views: 266
Reputation: 7121
In general, if you want to sum-then-round on the backend, you want to display rounded line-items, and you want the rounded line items to add up to the same total, then at least one of the line items might have to be rounded incorrectly by up to a penny. Your only option is to break at least one of those requirements. Some possible ways to do that (which you should run by a lawyer familiar with your jurisdiction/business) include:
Upvotes: 1