lookininward lookininward - 4 years ago 178
Python Question

How can I get Python to work on int inputs, converting them to two decimal points?

This program is intended to do the following:


  • Calculate the purchase price (including commission fee) of stocks purchased.

  • Calculate the sale price (including commission fee) of stocks purchased.



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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download