Python 2.7 の文字列フォーマットを使用して、リンゴ 10 個の価格をドルで出力しようとしています。単価はセントで指定されます。
の値を にしたいのですtotal_apple_cost
が"10.00"
、それは"1.001.001.001.001.001.001.001.001.001.00"
です。
他の変数のテストを含めて、それらがすべて期待どおりであることを示しました。
# 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'
解決:
変数「apple_cost_in_dollars」が文字列であることを示した以下の回答に感謝します。
私の解決策は、それをフロートにして、残りのコードをほぼ同じに保つことでした:
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'