Skip to main content
 首页 » 编程设计

python之从美分到美元的数字格式

2025年05月04日13birdshome

我正在尝试使用 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”是一个字符串。

我的解决方案是将其设为 float 并保持其余代码几乎相同:

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' 

请您参考如下方法:

因为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