1

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'
4

4 に答える 4

4

文字列であるためapple_cost_in_dollarsです。以下を参照してください

In [9]: cost = '1'

In [10]: cost * 10
Out[10]: '1111111111'

In [11]: cost = int('1')

In [12]: cost * 10
Out[12]: 10
于 2013-03-14T04:29:41.847 に答える
2

apple_costは、10 を掛ける文字列です (文字列を 10 回繰り返すだけです)。文字列としてフォーマットする前に、ドルに変換してください。

>>> apple_cost_in_cents = 100
>>> cents_to_dollars_format_string = '{:,.2f}'
>>> total_apple_cost_in_dollars_as_string = cents_to_dollars_format_string.format(10*apple_cost_in_cents/100.0)
>>> total_apple_cost_in_dollars_as_string
'10.00'

通貨の書式設定をさらに進めたい場合は、localeモジュール、特にlocale.currency関数を見ることができます。

于 2013-03-14T04:35:37.970 に答える
1
>>> import locale
>>> apple_cost_in_cents = 100
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
>>> locale.currency(apple_cost_in_cents * 10 / 100)
'$10.00'
于 2013-03-14T04:50:35.387 に答える
1

文字列 (テキスト) にフォーマットされました。したがって、10 * string_variable と書くと、その文字列が 10 回繰り返されます。最も簡単な方法は、次の行を変更することです。

total_apple_cost = 10 * apple_cost

に:

total_apple_cost = cents_to_dollars_format_string.format(10 * apple_cost_in_cents/100)

于 2013-03-14T04:51:09.510 に答える