Reputation: 671
This program is intended to do the following:
I would like the numbers to be accurately calculated to two decimal places. The issue is that if the user does not include decimals during input then the program doesn't recognize the decimal places.
This is why I've added the "broker_purchase_commission / 100.00" line, thinking it would force calculations to two decimal places. However, this does not appear to work. Any help is appreciated.
shares_purchased = input("How many shares were bought? ")
share_initial_price = input("What was the price per share? $")
broker__purchase_commission = input("What percentage commission is due to the stockbroker? ")
broker__purchase_commission = broker__purchase_commission / 100.00
purchase_price = ((shares_purchased * share_initial_price) + ((shares_purchased * share_initial_price) * broker__purchase_commission))
print ""
print "You purchased stock worth $%d" %purchase_price
print "Two weeks later you decide to sell the stock."
print ""
shares_sold = input("How many shares are sold? ")
share_present_price = input("What is the price per share? $")
broker__sale_commission = input("What percentage commission is due to the stockbroker? ")
broker__sale_commission = broker__sale_commission / 100.00
sale_price = ((shares_sold * share_present_price) + ((shares_sold * share_present_price) * broker__purchase_commission))
print "You sold stock worth $%d" %sale_price
Upvotes: 1
Views: 66
Reputation: 10951
Just use string formatting, mentioning the number of decimal to print:
>>> x = 1.0/10
>>> x
0.1
>>> print '%.2f' % x
0.10
>>> print '%.3f' % x
0.100
So in your code, you code apply it this way:
print "You sold stock worth ${:.2f}".format(sale_price)
Upvotes: 0
Reputation: 4656
For money stuff, you need precision, you must use the decimal module and convert all your numbers to Decimal like:
from decimal import *
Decimal(number)
So you should cast all the input to Decimal like
shares_purchased = Decimal(input("How many shares were bought? ")).
and also cast 100.00
to Decimal in your division by using Decimal(100.00)
.
For printing, make sure you do not cast the result to integer.
print "You purchased stock worth ", purchase_price
instead of
print "You purchased stock worth $%d" %purchase_price
See https://docs.python.org/2/library/decimal.html for the doc of the module.
Upvotes: 2