I'm trying to use Python 2.7's string formatting to output in dollars the cost of ten apples, where the unit price is provided in cents.
I would like the value of total_apple_cost
to be "10.00"
, but it's "1.001.001.001.001.001.001.001.001.001.00"
.
I have included tests for the other variables to show that they are all coming out as expected:
# define apple cost in cents
apple_cost_in_cents = 100
# define format string
cents_to_dollars_format_string = '{:,.2f}'
# convert 100 to 1.00
apple_cost_in_dollars = cents_to_dollars_format_string.format(apple_cost_in_cents / 100.)
# assign value of 'apple_cost_in_dollars' to 'apple_cost'
apple_cost = apple_cost_in_dollars
# calculate the total apple cost
total_apple_cost = 10 * apple_cost
# print out the total cost
print 'total apple cost: ' + str(total_apple_cost) + '\n'
#testing
print 'cost in cents: ' + str(apple_cost_in_cents) + '\n'
print 'cost in dollars: ' + str(apple_cost_in_dollars) + '\n'
print 'apple cost: ' + str(apple_cost) + '\n'
solution:
thank you to answers below which both indicated that the variable 'apple_cost_in_dollars' was a string.
my solution was to make it a float and keep the rest of the code pretty much the same:
apple_cost_in_cents = 100
cents_to_dollars_format_string = '{:,.2f}'
apple_cost_in_dollars = float(cents_to_dollars_format_string.format(apple_cost_in_cents / 100.))
apple_cost = apple_cost_in_dollars
total_apple_cost = 10 * apple_cost
print 'cost in cents: ' + str(apple_cost_in_cents) + '\n'
print 'cost in dollars: $''{:,.2f}'.format(apple_cost_in_dollars) + '\n'
print 'apple cost: $''{:,.2f}'.format(apple_cost) + '\n'
print 'total apple cost: $''{:,.2f}'.format(total_apple_cost) + '\n'
it is because apple_cost_in_dollars
is a string, see below
In [9]: cost = '1'
In [10]: cost * 10
Out[10]: '1111111111'
In [11]: cost = int('1')
In [12]: cost * 10
Out[12]: 10