2013-03-14 81 views
1

我正在嘗試使用Python 2.7的字符串格式輸出美元十個蘋果的成本,其中單位價格以美分提供。數字格式從美分到美元

我希望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

這是因爲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 
+0

打我吧:) +1 – mgilson 2013-03-14 04:30:09

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功能走得更遠。

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