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.
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:
Adjust the backend code. I'd personally find it a bit surprising if, e.g., a 15% tip weren't rounded to the nearest cent even as a line item.
Don't display some of the line items (or, e.g., group the Tax and Tip into a single line so that when grouped the sum-then-round and round-then-sum strategies match)
Just use the frontend total rather than the backend total, eating the <=$0.005 loss as a business to avoid customer service issues.
Display extra precision to the end user.
Include a footnote/FAQ to educate the user about a potential discrepency.
Adjusting some of the line items to include the missing pennies.
Related
I want to know what percentage of people that agree or strongly agree with a 1-100 rating scale in Python. I can use .describe() but it won't tell me what percentage of people chose 60 or higher.
The question is a statement and respondents must click 1 (Strongly Disagree) to 100 (Strongly Agree).
How do I get the percentage breakdown for respondents that said 60 or higher?
Thank you!
One simple way to do this is to make a new column and take the mean:
Q2['newcol'] = Q2['I fully enjoy ...'] >= 60
print(Q2['newcol'].mean())
That should give you the correct fraction.
The idea here is that we translate the response into a 0 or 1 binary value; the mean of this data is then the sum of those values divided by the count, which is equal to the number of 1s divided by the count, i.e. the fraction of people who gave a matching (i.e., >= 60) answer.
I have already written the program but when I run it I am getting shorted by one penny. (The problem is at the very bottom)
My instructor said it was fine because we haven't learned what to add to the string (?) to prevent that from happening, but said we could try and find out what to add if we wanted to.
Here's the the problem:
price=float(input("What is the price of the item?"))
tax=round(price*0.0725,2)
grandTotal=price+tax
tendered=float(input("How much money did customer give you?"))
print(format("The price of the item is $","26"), format(price,"6.2f"))
print(format("The tax on the item is","26"), format(tax, "6.2f"))
print(format("The total cost is","26"), format(grandTotal, "6.2f"))
print(format("You tendered","26"), format(tendered, "6.2f"))
change=tendered-grandTotal
print(format("Your change is","26"), format(change, "6.2f"))
Calculating the breakdown of change
penny=int(change*100) #transform change into pennies
dollars=penny//100 #how many dollars are there
pennyleft= penny%100 #remainder operator to find how many pennies are left
quarters= pennyleft//25 #number of quarters
pennyleft=pennyleft%25 #remainder operator to find how many pennies are left
dimes=pennyleft//10 #number of dimes
pennyleft=pennyleft%10
nickels=pennyleft//5 #number of nickels
pennyleft=pennyleft%5
pennies=pennyleft//1 #number of pennies
pennyleft=pennyleft%1
print("Your change is:")
print( format(dollars, "5"), "dollar bills,")
print( format(quarters, "5"), "quarters,")
print( format(dimes, "5"), "dimes,")
print( format(nickels, "5"), "nickels, and")
print( format(pennies, "5"), "pennies.")
And this is the output;
What is the price of the item?5.00
You owe a total of $ 5.36
How much money did customer give you?10.00
The price of the item is $ 5.00
The tax on the item is 0.36
The total cost is 5.36
You tendered 10.00
Your change is 4.64
Your change is:
4 dollar bills,
2 quarters,
1 dimes,
0 nickels, and
3 pennies.
So my issue is that the 3 pennies should actually be 4. Any suggestions on how to fix this?
Thank you!
You are working with floating point numbers, and as such the result may be just a bit more or less than you'd expect. Not all floating point numbers can be stored exactly in a computer. It may sound suprising but it's really not that different from the usual decimal system. After all, you cannot "store" 1/3 in a decimal number either! It will be 0.3333333... (an infinite amount of 3s omitted for clarity and lack of storage space).
If you test the values you get by printing out more decimals, you will find that this line
print(format("Your change is","26"), format(change, "6.20f"))
shows
Your change is 4.63999999999999968026
and, since int(x) always rounds down (more specifically, it "truncates towards zero" (documentation)), the next line
penny=int(change*100)
only cuts off the excess decimals so you end up with 463. After this, the number is converted to an integer and so no further floating point mishaps occur – but it's too late.
To get the proper calculation, all you have to do is add another round:
penny=int(round(change*100)) #transform change into pennies
and this will reimburse that lost penny.
I am a beginner at python and I'm struggling with one of my (simple) college assignments. I have been given the following instructions:
A bank is offering a savings account where a yearly fee is charged. Write
a program that lets the user enter
An initial investment.
The yearly interest rate in percent.
The yearly fee.
the program should then calculate the time it takes
for the investment to double. The interest is added on once per year.
An example run of the program:
Enter the investment: 1000
Enter the interest rate: 10
Enter the fee: 10
The investment doubles after 7 years.
I have formulated the following code but am receiving an error message with regards to t. I would really appreciate if I could get some help, thanks!:
t=0
p=float(input("Enter the investment:"))
a=float(input("Enter the interest rate:"))
m=float(input("Enter the fee:"))
i=(float(a/100))
f=p
while f<=(2*p):
f=(float(f*((1+i)**t)-m)
t=t+1
print("The investment doubles after",t,"years")
I tried to write this in a way that was very easy to follow and understand. I edited it with comments to explain what is happening line by line. I would recommend using more descriptive variables. t/p/a/m/f may make a lot of sense to you, but going back to this program 6 months from now, you may have issues trying to understand what you were trying to accomplish. NOTE You should use input instead of raw_input in my example if using Python 3+. I use 2.7 so I use raw_input.
#first we define our main function
def main():
#investment is a variable equal to user input. it is converted to a float so that the user may enter numbers with decimal places for cents
investment = float(raw_input("Starting Investment: "))
#interest is the variable for interest rate. it is entered as a percentage so 5.5 would equate to 5.5%
interest = float(raw_input("Interest Rate as %, ex: 5.5 "))
#annual_fee is a variable that will hold the value for the annual fee.
annual_fee = float(raw_input("Annual Fee: "))
#years is a variable that we will use with a while loop, adding 1 to each year (but we wait until within the loop to do this)
years = 1
#we use a while loop as opposed to a for loop because we do not know how many times we will have to iterate through this loop to achieve a result. while true is always true, so this segment is going to run without conditions
while True:
#this is a variable that holds the value of our total money per year, this is equal to the initial investment + investment * interest percentage - our annual fee per year
#I actually had to try a few different things to get this to work, a regular expression may have been more suited to achieve an interest % that would be easier to work with. do some research on regular expressions in python as you will sooner or later need it.
total_per_year = investment + (years * (investment * (interest / 100))) - (annual_fee * years)
#now we start adding 1 to our years variable, since this is a while loop, this will recalculate the value of total_per_year variable
years += 1
#the conditional statement for when our total_per_year becomes equal to double our initial investment
if total_per_year >= 2 * investment:
#print years value (at time condition is met, so it will be 5 if it takes 5 years) and the string ' Years to Double Investment'
print years,' Years to Double Investment'
#prints 'You will have $' string and then the value our variable total_per_year
print 'You will have $', total_per_year
#this will break our while loop so that it does not run endlessly
break
#here is error handling for if the fee is larger than investment + interest
if (years * annual_fee) >= (years * (investment * (interest / 100))):
print('Annual Fee Exceeds Interest - Losing Money')
break
#initial call of our main function/begins loop
main()
Note: I'm already using decimal.Decimal
What is the best way to perform and display calculations to the end user when you are required to output in the following rough style:
Item - £ 70.10
Item - £ 5.67
Item - £ 10.33
--------------
Total £ 86.10
I was always taught in maths as a kid to not round before your final answer, else you'll lose precision, but in this case if you don't it looks like we have calculation errors. as the calculation behind the display is not the same as the user would do from the numbers displayed to them.
EG:
My app will be doing: 70.1034 + 5.6693 + 10.333333333 = 86.1060333 (86.11 2dp)
My end user will be doing as above: 70.10 + 5.67 + 10.33 = 86.10
Therefore i appear to be incorrect. What is the best way to overcome this? (I mean generally, but python specific methods will help too)
Use the decimal module to get math that works out correctly. You can set it so each value will automatically use two decimal places.
>>> decimal.getcontext().prec = 2
>>> decimal.Decimal(1)/decimal.Decimal(3)
Decimal('0.33')
When you're working with money, it's normal to lose precision at each intermediate calculation.
(I asked this question earlier today, but I did a poor job of explaining myself. Let me try again)
I have a client who is an industrial maintenance company. They sell service agreements that are prepaid 20 hour blocks of a technician's time. Some of their larger customers might burn through that agreement in two weeks while customers with fewer problems might go eight months on that same contract. I would like to use Python to help model projected sales revenue and determine how many billable hours per month that they'll be on the hook for.
If each customer only ever bought a single service contract (never renewed) it would be easy to figure sales as monthly_revenue = contract_value * qty_contracts_sold. Billable hours would also be easy: billable_hrs = hrs_per_contract * qty_contracts_sold. However, how do I account for renewals? Assuming that 90% (or some other arbitrary amount) of customers renew, then their monthly revenue ought to grow geometrically. Another important variable is how long the average customer burns through a contract. How do I determine what the revenue and billable hours will be 3, 6, or 12 months from now, based on various renewal and burn rates?
I assume that I'd use some type of recursive function but math was never one of my strong points. Any suggestions please?
Edit: I'm thinking that the best way to approach this is to think of it as a "time value of money" problem. I've retitled the question as such. The problem is probably a lot more common if you think of "monthly sales" as something similar to annuity payments.
If you want to consider the problem in terms of present value of future revenue (that's what "time value of money" implies to me), then you have the following parameters: discount rate D (on a monthly basis for convenience), time T a customer will take to exhaust their prepaid hours, likelihood L that they will renew when their prepaid hours are up, dollar amounts for first sale F and renewal R. This has several assumptions of course (maybe the customers who consume support faster are more likely to renew, for example -- this model doesn't account for that) but it may still be a useful first approximation.
So making a sale today is worth: F immediately for sure; plus, in T months, R more with probability L; plus, in 2T months, R more with probability LL; and so on. So the worth of that sale is F + RL / (DT) + RLL / (D2T) + ... = F + (R*L / DT ) * (1 + L/DT + L2/(DT)**2 + ...).
The series converges to 1 / (1 - L/(D**T)), so the overall formula in closed form (shifting to Python;-):
def salesworth(D, T, L, F, R):
return F + (R * L) / (D**T * (1 - L / (D**T)))
Expected billable hours can be had with the same formula, just using for F and R the number of hours in a first sale and renewal, and (if the discount rate concept does not apply to billable hours) a D of 1 (so T doesn't actually matter, as 1**T == 1 for any T;-).
Thanks for the assistance even though my requirements were a bit vague. After consulting someone who is extremely versed in financial mathematics, I determined that a simple formula was not an appropriate solution.
What I ended up doing is "exploding" the months into the component days using xrange() and iterating over each day. When evaluating each day, I determined whether a new contract was signed on that day, and if so, which dates in future the contract would need to be renewed. I pushed those renewal dates into a list and then summed the values.